【FROM MSDN && 百科】
原型: char *strtok(char *s, const char *delim);
#include<string.h>
分解字符串爲一組字符串。s爲要分解的字符串,delim爲分隔符字符串。
strtok()用來將字符串分割成一個個片段。參數s指向欲分割的字符串,參數delim則爲分割字符串中包含的所有字符。當strtok()在參數s的字符串中發現參數delim中包涵的分割字符時,則會將該字符改爲\0
字符。在第一次調用時,strtok()必需給予參數s字符串,往後的調用則將參數s設置成NULL。每次調用成功則返回指向被分割出片段的指針。
s開頭開始的一個個被分割的串。當沒有被分割的串時則返回NULL。所有delim中包含的字符都會被濾掉,並將被濾掉的地方設爲一處分割的節點。
DEMO:MSDN上的
#include <stdio.h>
#include <string.h>
#include <conio.h>
char string[] = "A string\tof ,,tokens\nand some more tokens";
char seps[] = " ,\t\n";
char *token;
int main(void)
{
printf( "Tokens:\n" );
token = strtok( string, seps );
while(token !=NULL)
{
printf("%s\n",token);
token=strtok(NULL,seps);
}
getch();
return 0;
}
DEMO:
#include <stdio.h>
#include <conio.h>
int main(void)
{
char input[16]="abc,d,yuwen";
char *p;
p=strtok(input,",");
if (p)
{
printf("%s\n",p);
}
p=strtok(NULL,",");
if (p)
{
printf("%s\n",p);
}
getch();
return 0;
}