原型
char* strtok(char* s,const char* delim)功能
分解字符串为一组字符串,s为要分解的字符串,delim为分隔符字符串,当在参数s 的字符串中发现到字符串delim 时,则会将该字符改为\0 字符。在第一次调用时,strtok()必需给予参数s 字符串,往后的调用则将参数s 设置成NULL。每次调用成功则返回下一个分割后的字符串指针返回值
若str2是str1的子串,则返回str2在str1的首次出现的地址如果str2不是str1的子串,则返回NULL
示例
#include <string.h>
#include <iostream.h>
void main(void)
{
char input[100]="abc,d,ef,ghi,jk,lmno";
int i=0;
char *p = input;
while ((p=strtok(p,",")) != NULL)
{
i++;
cout<<"split str"<<i<<":"<<p<<endl;
p = NULL;
}
cout<<"input:"<<input<<endl;
}
结果:
split str1:abc
split str2:d
split str3:ef
split str4:ghi
split str5:jk
split str6:lmno
input:abc
注意
该函会破坏被分解字符串的完整,由上面的例子可看出,input在调用前后已经不一样了。
strtok_s
strtok_s是windows下的一个分割字符串安全函数,函数原型:
char *strtok_s( char *strToken, const char *strDelimit, char **buf);
这个函数将剩余的字符串存储在buf变量中,而不是静态变量中,从而保证了安全性。
strtok_r
strtok_s函数是linux下分割字符串的安全函数,函数 原型:char *strtok_r(char *str, const char *delim, char **saveptr);