strsep

函数原型:
     
  1. Char * strsep(char **s1, const char *delimt); 
需要注意:
1、         被分割字串要被改变,所以不能操作存放在静态存储区的字串常量。
2、        分割符要被替换成’\0’。
3、        需要传二级指针,因为s1是指向分割字串,第一次指向源字串,调用后指向分割后的下一个token。所以s1会改变,需要传递二级指针。
对于注意1,常犯错误如下:
  1. char *str = "This is a example to test the function of strsep";  
  2. strsep(&str, " "); 

str指向的字串是静态存储区,属于字符串常量,不能修改。会出现段错误。

而对于注意3,常犯错误如下:

 

  1. char str[] = "This is a example to test the function of strsep";  
  2. strsep(&str, " "); 

&str是一级指针,所以也会出现段错误。

       其实对于会修改源字串的函数都容易出现上面的错误。用时要格外小心注意。

strtok也跟strsep一样,是用来分割字符串的,但不同的是strtok把待分割字串和遍历指针分开,并且遍历指针也是内置的。但是strsep把待分割字串和内置指针整合,所以需要传二级指针。

函数原型:

  1. char *strtok(char *s1, const char *delim); 

同样注意上面的错误地方。

strtok要对同一字串进行多次分割,第一次需要指定源字串,接下来需要传NULL;而strsep则不需关心这个问题,因为它是把待分割字串的二级指针传过去,内部会进行指针的后移。

strsep使用如下:

 

  1. char *str = strdup("This is a example to test the function of strsep");  
  2. char *p = NULL;  
  3. while(NULL != ( p = strsep(&str, " "))  
  4. {  
  5.     puts(p);  

而strtok使用如下:

第一次要指定待分割字串,接下来则要传NULL。

  1. char *str = strdup("This is a example to test the function of strsep");  
  2. char *p = NULL;  
  3. char *tmp = str;  
  4. while (NULL != (p = strsep(tmp, " ")))  
  5. {  
  6.     puts(p);  
  7.     tmp = NULL;