C++中用strtok()完成字符串切割

C++中用strtok()完成字符串切割

函数原型::char *strtok(char s[], const char *delim);

函数说明:C/C++中strtok()函数主要用来将字符串进行切割,类似Python中的split函数的功能,其中参数s主要指向想要切割的目标字符串,delim指向的是分隔符,当strtok()在参数s的字符串中发现参数delim中包含的分割字符时,则会将该字符改为\0(NULL) 字符

函数使用:首次调用时,s指向要分解的字符串,之后再次调用要把s设成NULL。函数每次调用之后,返回值为分割后的字符串指针,如果分割全部结束,返回NULL

使用示例:

#include
#include
using namespace std;

int main()
{
char s[] = “wo yao kai fei ji”;
cout<<“the primary sentence is :”<<s<<endl;
char *tokenptr = strtok(s, " ");
while(tokenptr != NULL)
{
cout<<tokenptr<<endl;
tokenptr = strtok(NULL, " "); //第二个参数为空格
}
cout<<“the last sentence is :”<<s<<endl;
return 0;
}

结果:
C++中用strtok()完成字符串切割