编程时在C中需要用的类似Java的Split函数来解析一个长字符串,分割成子段使用,查函数库发现有strtok可用,看了示例却对它的用法有些疑惑为什么传值是NULL,于是上网查资料,找到这篇包含strtok函数源码的解释,转过来学习,仔细研读收获良多。
查函数库看到的strtok的解释和示例:
#include <cstring> char *strtok( char *str1, const char *str2 );
The strtok() function returns a pointer to the next "token" in str1, where str2 contains the delimiters that determine the token. strtok() returns NULL if no token is found. In order to convert a string to tokens, the first call to strtok() should have str1 point to the string to be tokenized. All calls after this should have str1 be NULL.
For example:
char str[] = "now # is the time for all # good men to come to the # aid of their country"; char delims[] = "#"; char *result = NULL; result = strtok( str, delims ); while( result != NULL ) { printf( "result is /"%s/"/n", result ); result = strtok( NULL, delims ); }
The above code will display the following output:
result is "now " result is " is the time for all " result is " good men to come to the " result is " aid of their country"
下面是查到的网络文章对源码的解释:
原型:char * strtok(char * s,const char * ct)
用途:在s中找出以ct中的字符为分隔的字符串,即是源串中除去了含有分隔串中的所有字符后余下的一段段的字符串,每调用一次找到一串,找不到则返回空串。第一次调用必须传给它有效的字符串,第二次传NULL就可以了,每次调用返回找到的子串的时候都会把源串中该子串的尾部字符(原来是搜索串中的某一字符)修改成'/0'字符返回值为每次调用得到的字串。
下面看一下它的使用
///char *pbody= "Presetptz/r/nPreset1=hello/r/nPreset2=ttttt/r/nend/r/n";//errror
下面我们看一下它的源码:
char *___strtok;//关键这个全局指针变量
char * strtok(char * s,const char * ct)
{
}
其中:
char * strpbrk(const char * cs,const char * ct)//返回指向ct中任一字符在cs中第一次出现的位置
这个函数不难分析,___strtok指针指向除去第一个有效字串后面的位置,到这里我们应该清楚为什么第二次调用时只要传NULL就可以了,当然这里也暴露了它的缺点,就是说不能有两个线程同时使用strtok否则就会出现错误。还有就是我在使用这个函数时碰到的问题,如上面的代码如果我把sbody换成 pbody,则编译没有问题,运行时就会出错,为什么?还是自己的基本功不扎实,pbody在是个静态字符串,说白了,它是在编译时就已经赋值而且相当于是一个const常量,不能被修改,而strtok是需要修改字符串的,所以产生问题不足为奇。