之前用java分解过字符串,貌似用的是正则式,意外发现c++里面也有strtok函数
1)库函数 #include<cstring>
2)作用 把字符串分解成一系列的记号token,记号是用分隔符分离出来的字符序列。例如把“i love you”按空格分解就可以得到“i" "love" "you"
3)原理 第一次strtok(char *arr,char *) token从第一个不是分隔符的字符开始标记,发现分隔符时,将其替换成'\0',将该记号后面的一个字符位置放到一个程序员不可见的静态变量中,返回一个当前位置的指针。第二次调用时,用NULL作第一个参数,NULL调用上次函数保存的位置,当没有剩余记号时,返回NULL;
4)注意 字符串到最后是被改变了的
5)程序
#include <iostream>
#include<cstring>
using namespace std;
void main()
{
char s[]="this is love for you and me";
char *token;
cout<<"string is"<<s<<endl;
token=strtok(s," ");
while(token!=NULL)
{
cout<<token<<"\n";
token=strtok(NULL," ");
}
cout<<"last :"<<s<<endl;
}
#include<cstring>
using namespace std;
void main()
{
char s[]="this is love for you and me";
char *token;
cout<<"string is"<<s<<endl;
token=strtok(s," ");
while(token!=NULL)
{
cout<<token<<"\n";
token=strtok(NULL," ");
}
cout<<"last :"<<s<<endl;
}