這幾天處理字符串,突然遇到字符串分割問題,上網查了一些資料后,找到這兩個函數,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,有興趣的可以研究一下。它適用於分割關鍵字在字符串之間是“單獨”或是 “連續“在一起的情況。
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");
編譯通過,運行時會報段錯誤。