STRTOK

char *strtok(char *s, const char *delim);

分解字符串为一组字符串。s为要分解的字符串,delim为分隔符字符串。

strtok()用来将字符串分割成一个个片段。参数s指向欲分割的字符串,参数delim则为分割字符串,当strtok()在参数s的字符串中发现到参数delim的分割字符时则会将该字符改为\0 字符。在第一次调用时,strtok()必需给予参数s字符串,往后的调用则将参数s设置成NULL。每次调用成功则返回被分割出片段的指针

 1 #include <iostream>   
 2 #include <cstring>   
 3 using namespace std;   
 4 int main()   
 5 {   
 6      char sentence[]="This is a sentence with 7 tokens";   
 7      cout<<"The string to be tokenized is:\n"<<sentence<<"\n\nThe tokens are:\n\n";   
 8      char *tokenPtr=strtok(sentence," ");   
 9      while(tokenPtr!=NULL)   
10      {   
11           cout<<tokenPtr<<'\n';   
12           tokenPtr=strtok(NULL," ");   
13      }   
14           //cout<<"After strtok, sentence = "<<tokenPtr<<endl;   
15      return 0;   
16 }   
17 函数第一次调用需设置两个参数。
18 第一次分割的结果,返回串中第一个 ',' 之前的字符串,也就是上面的程序第一次输出abc。   
19 第二次调用该函数strtok(NULL,","),第一个参数设置为NULL。结果返回分割依据后面的字串,即第二次输出d。   
20 strtok是一个线程不安全的函数,因为它使用了静态分配的空间来存储被分割的字符串位置 
原文地址:https://www.cnblogs.com/hxsyl/p/2707846.html