字符串分割函數strtok()

分解字符串爲一組字符串。s爲要分解的字符串,delim爲分隔符字符串。

例如:strtok("abc,def,ghi",","),最後可以分割成爲abc def ghi.尤其在點分十進制的IP中提取應用較多。

strtok()用來將字符串分割成一個個片段。參數s指向欲分割的字符串,參數delim則爲分割字符串中包含的所有字符。當strtok()在參數s的字符串中發現參數delim中包涵的分割字符時,則會將該字符改爲\0 字符。在第一次調用時,strtok()必需給予參數s字符串,往後的調用則將參數s設置成NULL。每次調用成功則返回指向被分割出片段的指針。

strtok函數會破壞被分解字符串的完整,調用前和調用後的s已經不一樣了。如果

要保持原字符串的完整,可以使用strchr和sscanf的組合等。

c

#include <string.h>

#include <stdio.h>

int main(void)

{

char input[16] = "abc,d";

char *p;

/**/ /* strtok places a NULL terminator

in front of the token, if found */

p = strtok(input, ",");

if (p) printf("%s\n", p);

/**/ /* A second 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<<'\n';

tokenPtr=strtok(NULL," ");

}

//cout<<"After strtok, sentence = "<<tokenPtr<<endl;

return 0;

}

函數第一次調用需設置兩個參數。第一次分割的結果,返回串中第一個 ',' 之前的字符串,也就是上面的程序第一次輸出abc。

第二次調用該函數strtok(NULL,","),第一個參數設置爲NULL。結果返回分割依據後面的字串,即第二次輸出d。

strtok是一個線程不安全的函數,因爲它使用了靜態分配的空間來存儲被分割的字符串位置

線程安全的函數叫strtok_r,ca

運用strtok來判斷ip或者mac的時候務必要先用其他的方法判斷'.'或':'的個數,因爲用strtok截斷的話,比如:"192..168.0...8..."這個字符串,strtok只會截取四次,中間的...無論多少都會被當作一個key


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章