-
strtok
鎖定
- 外文名
- strtok
- 功 能
- 分解字符串為一組字符串
- 原 型
- char *strtok(char s[], const char *delim)
- delim
- 分隔符字符串
- 頭文件
- string.h
strtok原型
char *strtok(char s[], const char *delim);
strtok功能
分解字符串為一組字符串。s為要分解的字符串,delim為分隔符字符串。
例如:strtok("abc,def,ghi",","),最後可以分割成為abc def ghi.尤其在點分十進制的IP中提取應用較多。
strtok的函數原型為char *strtok(char *s, char *delim),功能為“Parse S into tokens separated by characters in DELIM.If S is NULL, the saved pointer in SAVE_PTR is used as the next starting point. ” 翻譯成漢語就是:作用於字符串s,以包含在delim中的字符為分界符,將s切分成一個個子串;如果,s為空值NULL,則函數保存的指針SAVE_PTR在下一次調用中將作為起始位置。
strtok説明
strtok()用來將字符串分割成一個個片段。參數s指向欲分割的字符串,參數delim則為分割字符串中包含的所有字符。當strtok()在參數s的字符串中發現參數delim中包含的分割字符時,則會將該字符改為\0 字符。在第一次調用時,strtok()必需給予參數s字符串,往後的調用則將參數s設置成NULL。每次調用成功則返回指向被分割出片段的指針。
strtok返回值
從s開頭開始的一個個被分割的串。當s中的字符查找到末尾時,返回NULL。
如果查找不到delim中的字符時,返回當前strtok的字符串的指針。
所有delim中包含的字符都會被濾掉,並將被濾掉的地方設為一處分割的節點。
strtok使用
c
#include<string.h> #include<stdio.h> int main(void) { char input[16]="abc,d"; char*p; /*strtok places a NULL terminator infront of the token,if found*/ p=strtok(input,","); if(p) printf("%s\n",p); /*Asecond call to strtok using a NULL as the first parameter returns a pointer to the character following the token*/ p=strtok(NULL,","); if(p) printf("%s\n",p); return 0; }
c++
#include<iostream> #include<cstring> using namespace std; int main() { char sentence[]="This is a sentence with 7 tokens"; cout << "The string to be tokenized is:\n" << sentence << "\n\nThe tokens are:\n\n"; char *tokenPtr=strtok(sentence," "); while(tokenPtr!=NULL) { cout<<tokenPtr<<endl; tokenPtr=strtok(NULL," "); } //cout << "After strtok,sentence=" << tokenPtr<<endl; return 0; }
函數第一次調用需設置兩個參數。第一次分割的結果,返回串中第一個 ',' 之前的字符串,也就是上面的程序第一次輸出abc。
第二次調用該函數strtok(NULL,","),第一個參數設置為NULL。結果返回分割依據後面的字串,即第二次輸出d。
線程安全的函數叫strtok_r,ca
運用strtok來判斷ip或者mac的時候務必要先用其他的方法判斷'.'或':'的個數,因為用strtok截斷的話,比如:"192..168.0...8..."這個字符串,strtok只會截取四次,中間的...無論多少都會被當作一個key
其他相關信息
下面的説明摘自於Linux內核2.6.29,説明了這個函數已經不再使用,由速度更快的strsep()代替
/** linux/lib/string.c** Copyright (C) 1991, 1992 Linus Torvalds*//** stupid library routines.. The optimized versions should generally be found
* These are buggy as well..
* * Fri Jun 25 1999, Ingo Oeser <ioe@informatik.tu-chemnitz.de>
* - Added strsep() which will replace strtok() soon (because strsep() is
* reentrant and should be faster). Use only strsep() in new code, please.
* Matthew Hawkins <matt@mh.dropbear.id.au>
* - Kissed strtok() goodbye
- 參考資料
-
- 1. strtok()和strtok_r() .博客園[引用日期2013-04-09]