strtok_r 和 strsep 使用实例
strsep() function was introduced as a replacement for strtok(3), since the latter cannot handle empty fields. However, strtok(3) conforms to?C89/C99 and hence is more portable.
也就是說strsep是strtok的替代接口,但可能在移植的時候會出現問題。
#include <stdio.h> #include <string.h> #include <stdlib.h> int main() { char ptr[]={ "abc;defghijk; lmnopqrst ;uvwxyz "}; char *p = ptr, *str= "; "; int i = 0;char *sep = NULL;printf("Original string : %s\n", ptr);while((sep = strsep(&p, str)) != NULL){if(!strcmp(sep, "")){printf("more than %s appear \n", sep);continue;}printf("Line %d: %s\n", ++i, sep); }return 0; } 輸出結果:TestServer $ ./strsep?
Original string : abc;defghijk; ? ? lmnopqrst ;uvwxyz?
Line 1: abc
Line 2: defghijk
more than ?appear?
more than ?appear?
more than ?appear?
more than ?appear?
more than ?appear?
Line 3: lmnopqrst
more than ?appear?
Line 4: uvwxyz
more than ?appear?
會多次出現空字符串的問題,這是因為strsep在處理多余一個的delimit字符是會返回空字符串代替NULL。
#include <stdio.h> #include <string.h> #include <stdlib.h> int main() { char ptr[]={ "abc;defghijk; lmnopqrst ;uvwxyz "}; char *p = ptr, *dlm= "; "; int i = 0;char *sep = NULL, *saveptr = NULL;printf("Original string : %s\n", ptr);while((sep = strtok_r(p, dlm, &saveptr)) != NULL){printf("Line %d: %s\n", ++i, sep); // note: p have to set NULL, or will not break while();p = NULL;}return 0; }輸出結果:TestServer$ ./strtok_r Original string : abc;defghijk; lmnopqrst ;uvwxyz?
Line?1: abc
Line?2: defghijk
Line?3: lmnopqrst
Line?4: uvwxyzstrtok?
函數會將多余一個delimit字符轉換成'\0', 注意p = NULL操作,在第二次調用strtok&strtok_r時需要將str=NULL。
總結
以上是生活随笔為你收集整理的strtok_r 和 strsep 使用实例的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: php 应用程序错误,系统化PHP中的W
- 下一篇: (4)编写一个程序,输出三角形字符阵列图