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; }