strsep
- Char * strsep(char **s1, const char *delimt);
- char *str = "This is a example to test the function of strsep";
- strsep(&str, " ");
str指向的字串是静态存储区,属于字符串常量,不能修改。会出现段错误。
而对于注意3,常犯错误如下:
- char str[] = "This is a example to test the function of strsep";
- strsep(&str, " ");
&str是一级指针,所以也会出现段错误。
其实对于会修改源字串的函数都容易出现上面的错误。用时要格外小心注意。
strtok也跟strsep一样,是用来分割字符串的,但不同的是strtok把待分割字串和遍历指针分开,并且遍历指针也是内置的。但是strsep把待分割字串和内置指针整合,所以需要传二级指针。
函数原型:
- char *strtok(char *s1, const char *delim);
同样注意上面的错误地方。
strtok要对同一字串进行多次分割,第一次需要指定源字串,接下来需要传NULL;而strsep则不需关心这个问题,因为它是把待分割字串的二级指针传过去,内部会进行指针的后移。
strsep使用如下:
- char *str = strdup("This is a example to test the function of strsep");
- char *p = NULL;
- while(NULL != ( p = strsep(&str, " "))
- {
- puts(p);
- }
而strtok使用如下:
第一次要指定待分割字串,接下来则要传NULL。
- char *str = strdup("This is a example to test the function of strsep");
- char *p = NULL;
- char *tmp = str;
- while (NULL != (p = strsep(tmp, " ")))
- {
- puts(p);
- tmp = NULL;
- }