◆ 使用strtok函數(shù)分割。
原型:char *strtok(char *s, char delim);
strtok在s中查找包含在delim中的字符并用NULL('\0')來替換,直到找遍整個(gè)字符串。
功能:分解字符串為一組字符串。s為要分解的字符串,delim為分隔符字符串。
說明:首次調(diào)用時(shí),s指向要分解的字符串,之后再次調(diào)用要把s設(shè)成NULL。
strtok在s中查找包含在delim中的字符并用NULL('\0')來替換,直到找遍整個(gè)字符串。
返回值:從s開頭開始的一個(gè)個(gè)被分割的串。當(dāng)沒有被分割的串時(shí)則返回NULL。
所有delim中包含的字符都會被濾掉,并將被濾掉的地方設(shè)為一處分割的節(jié)點(diǎn)。
使用例:
#include <stdio.h>
#include <string.h>
#include <stdio.h>
#include <string.h>
int main(int argc,char **argv)
{
char * buf1="aaa, ,a, ,,,bbb-c,,,ee|abc";
/* Establish string and get the first token: */
char* token = strtok( buf1, ",-|");
while( token != NULL )
{
/* While there are tokens in "string" */
printf( "%s ", token );
/* Get next token: */
token = strtok( NULL, ",-|");
}
return 0;
}
OUT 值:
aaa
a
bbb
c
ee
abc
◆ 使用strstr函數(shù)分割。
原型:extern char *strstr(char *haystack,char *needle);
用法:#include <string.h>
功能:從字符串haystack中尋找needle第一次出現(xiàn)的位置(不比較結(jié)束NULL)
說明:返回指向第一次出現(xiàn)needle位置的指針,如果沒找到則返回NULL。
使用例:
#include <stdio.h>
#include <string.h>
int main(int argc,char **argv)
{
char *haystack="aaa||a||bbb||c||ee||";
char *needle="||";
char* buf = strstr( haystack, needle);
while( buf != NULL )
{
buf[0]='\0';
printf( "%s\n ", haystack);
haystack = buf + strlen(needle);
/* Get next token: */
buf = strstr( haystack, needle);
}
return 0;
}
OUT 值:
aaa
a
bbb
c
ee
◆ strtok比較適合多個(gè)字符作分隔符的場合,而strstr適合用字符串作分隔符的場合。