您的位置:首页 > 编程语言 > C语言/C++

C++ 按指定分隔符拆分字符串

2016-03-09 20:19 453 查看
strtok函数可以帮忙,以下是例子:

例1:
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
char sentence[]="This is a sentence with 7 tokens";
cout<<"The string to be tokenized is:\n"<<sentence<<"\n\nThe tokens are:\n\n";
char *tokenPtr=strtok(sentence," ");
while(tokenPtr!=NULL)
{
cout<<tokenPtr<<'\n';
tokenPtr=strtok(NULL," ");
}
cout<<"After strtok, sentence = "<<sentence<<endl;
return 0;

}

例2:

#include <iostream>
#include<cstdlib>
#include<cstring>
using namespace std;

int main()
{
string strDate;
char arrDate[10];
int year = 0;
int month = 0;
int day = 0;
while(cin>>strDate){
strcpy(arrDate,strDate.c_str());

char *tokenPtr=strtok(arrDate,"/");
year = atoi(tokenPtr);
tokenPtr=strtok(NULL,"/");
month = atoi(tokenPtr);
tokenPtr=strtok(NULL,"/");
day = atoi(tokenPtr);
cout<<year<<" "<<month<<" "<<day<<endl;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: