strtok 与 strsep 函数说明
这几天处理字符串,突然遇到字符串分割问题,上网查了一些资料后,找到这两个函数,strtok与strsep函数。网上举的例子千篇一律,下面我根据函数的实现源码,记录一下使用说明,供大家讨论,欢迎大牛拍砖!PS:找个库函数源码的在线查询网站真不容易,先找到了这个http://sources.redhat.com/cgi-bin/cvsweb.cgi/libc/?cvsroot=glibc
之后,发现了经常去找软件的oschina有源码库,真是踏破铁鞋无觅处,得来全不费工夫!
http://www.oschina.net/code/explore/glibc-2.9/string/strtok.c
1 #include <stdio.h> 2 #include <string.h> 3 int main() 4 { 5 char token[] ="abdczxbcdefgh"; 6 printf("%s\n",token); 7 char *tokenremain = token; 8 char *tok1 = strtok(tokenremain,"cde"); 9 printf("tok1:%s\n",tok1); 10 tok1 = strtok(NULL,"cde"); 11 printf("tok1:%s\n",tok1); 12 return 0; 13 }
[root@ test]# ./strtok
abdczxbcdefgh
tok1:ab
tok1:zxb
总结:strtok内部记录上次调用字符串的位置,所以不支持多线程,可重入版本为strtok_r,有兴趣的可以研究一下。它适用于分割关键字在字符串之间是“单独”或是 “连续“在一起的情况。
C++中关于strtok()函数的用法
函数原型:char *strtok(char *s, const char *delim);
Function:分解字符串为一组字符串。s为要分解的字符串,delim为分隔符字符串。
Description:strtok()用来将字符串分割成一个个片段。参数s指向欲分割的字符串,参数delim则为分割字符串,当strtok()在参数s的字符串中发现到参数delim的分割字符时 则会将该字符改为\0 字符。在第一次调用时,strtok()必需给予参数s字符串,往后的调用则将参数s设置成NULL。每次调用成功则返回被分割出片段的指针。
#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;
}
/* 函数第一次调用需设置两个参数。第一次分割的结果,返回串中第一个 ',' 之前的字符串,也就是上面的程序第一次输出abc。
* 第二次调用该函数strtok(NULL,","),第一个参数设置为NULL。结果返回分割依据后面的字串,即第二次输出d。
* strtok是一个线程不安全的函数,因为它使用了静态分配的空间来存储被分割的字符串位置
* 线程安全的函数叫strtok_r,ca
* 运用strtok来判断ip或者mac的时候务必要先用其他的方法判断'.'或':'的个数,
* 因为用strtok截断的话,比如:"192..168.0...8..."这个字符串,strtok只会截取四次,中间的...无论多少都会被当作一个key
*/
http://www.oschina.net/code/explore/glibc-2.9/string/strsep.c
1 #include <stdio.h> 2 #include <string.h> 3 4 int main() 5 { 6 char token[] ="abdzxbcdefgh"; 7 printf("%s\n",token); 8 char *tokenremain = token; 9 char *tok1 = strsep(&tokenremain,"cde"); 10 printf("tok1:%s,token:%s\n",tok1,tokenremain); 11 tok1 = strsep(&tokenremain,"cde"); 12 printf("tok1:%s,token:%s\n",tok1,tokenremain); 13 return 0; 14 }
[root@ test]# ./strsep
abdzxbcdefgh
tok1:ab,token:zxbcdefgh
tok1:zxb,token:defgh
总结:strsep返回值为分割后的开始字符串,并将函数的第一个参数指针指向分割后的剩余字符串。它适用于分割关键字在两个字符串之间只严格出现一次的情况。
所以通过阅读函数实现源码,可以灵活运用这两个函数,为自己所用!
PS:因为函数内部会修改原字符串变量,所以传入的参数不能是不可变字符串(即文字常量区)。
如 char *tokenremain ="abcdefghij"//编译时为文字常量,不可修改。
strtok(tokenremain,"cde");
strsep(&tokenremain,"cde");
编译通过,运行时会报段错误。