原型:char *strsep(char **stringp, const char *delim);
功能:分解字符串為一組字符串。
示例:
#include <stdio.h>
#include <string.h>
int main(void)
{
char str[] = "root:x::0:root:/root:/bin/bash:";
char *buf;
char *token;
buf = str;
while((token = strsep(&buf, ":")) != NULL){
printf("%s\n", token);
}
return 0;
}
char *strtok(char *s, char *delim);
分解字符串為一組字符串。s為要分解的字符串,delim為分隔符字符串。
首次調(diào)用時(shí),s指向要分解的字符串,之后再次調(diào)用要把s設(shè)成NULL。
strtok在s中查找包含在delim中的字符并用NULL('')來替換,直到找遍整個(gè)字符串。
char * p = strtok(s,";");
p = strtok(null,";");
在調(diào)用的過程中,字串s被改變了,這點(diǎn)是要注意的。
從s開頭開始的一個(gè)個(gè)被分割的串。當(dāng)沒有被分割的串時(shí)則返回NULL。
所有delim中包含的字符都會(huì)被濾掉,并將被濾掉的地方設(shè)為一處分割的節(jié)點(diǎn)。
strtok函數(shù)在C和C++語言中的使用
strtok函數(shù)會(huì)破壞被分解字符串的完整,調(diào)用前和調(diào)用后的s已經(jīng)不一樣了。如果
要保持原字符串的完整,可以使用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 = "<<sentence<<endl;
return 0;
}