C庫中重要字串自動分割函式strtok
阿新 • • 發佈:2018-12-23
函式strtok
原型 char * strtok ( char * str, const char * delimiters );
功 能: 查詢由在第二個串中指定的分界符分隔開的單詞, 即源串中除去了含有分隔串中的所有字元後餘下的一段段的字串,每呼叫一次找到一串,找不到則返回空串。顯然函式會改變引數,因此不能用於常量如英文所描述。另外只能單執行緒安全。strtok使用注意事項:
* These functions modify their first argument.
* These functions cannot be used on constant strings.
* The identity of the delimiting character is lost.
* The strtok() function uses a static buffer while parsing, so it's not thread safe.
輸出如下:#include <stdio.h> #include <string.h> int main(){ char *str= "A stringtof ,,tokensnand some more tokens"; char str2[100]; char *seps = " ,\t\n"; char *token; int len,i; strcpy(str2,str); len=strlen(str); token = strtok(str2,seps); while( token != NULL ) { printf("%s ", token); token = strtok(NULL, seps); } printf("\n"); printf("%s\n",str); for(i=0;i<len;i++) if(str2[i]=='\0')//用特殊顏色打印出'\0'字元 printf("\033[0;30;41m.\033[0m"); else printf("%c",str2[i]); printf("\n"); }
A stringtof tokensnand some more tokens
A stringtof ,,tokensnand some more tokens
A.stringtof.,,tokensnand.some.more.tokens (結束符,用特殊符號 . 表示)
上圖中第一行是利用strtok進行分隔得到的多個字串,第2行是原始的字串str,第3行是用strtok處理後原始字串str2。
知識點:
strtok是對原始的字串進行修改的,是將其中的分隔字元替換為'\0',這樣每次呼叫strtok之後返回值指向當前找到的新字串的頭,而且從這個頭開始,所遇到的第一個分隔符已經替換為'\0',所以列印token可以得到分隔後的字串,並且由於這個函式使用了靜態變數所以可以利用迴圈不斷的進行操作。
這樣,既然我們明白了strtok是要對原始的字串進行修改,就應該注意到了,其引數不能是類似:
char *str= "A stringtof , ,tokensnand some more tokens"; 這樣的常量字串,因為這種是靜態儲存的,是不允許修改的,而只能是字元陣列形式的:
char str2[]= "A stringtof , ,tokensnand some more tokens";