//----------------------------------------------------
//AUTHOR: lanyang123456
//DATE: 2014-11-09
//---------------------------------------------------
函数原型:char *strtok(char *s, const char *delim);
Function:分解字符串为一组字符串。s为要分解的字符串,delim为分隔符字符串。
Description:strtok()用来将字符串分割成一个个片段。参数s指向要分割的字符串,参数delim则为分割字符串,当strtok()在参数s的字符串中发现参数delim的分割字符时, 则会将该字符改为\0 字符。在第一次调用时,strtok()必需给予参数s字符串,往后的调用则将参数s设置成NULL。每次调用成功则返回被分割出片段的指针。s必须是字符数组或者其他可写的存储区域,因为在搜索过程中,要修改字符串,即会将分隔符设置为‘\0’;
更具体些,函数strtok将字符串分解为一系列标记(token),标记就是一系列用分隔符(delimiting chracter,通常是空格或标点符号)分开的字符。注意,此的标记是由delim分割符分割的字符串。
例如,在一行文本中,每个单词可以作为标记,空格是分隔符。
需要多次调用strtok才能将字符串分解为标记(假设字符串中包含多个标记)。第一次调用strtok包含两个参数,即要标记化的字符串和包含用来分隔标记的字符的字符串(即分隔符);例如下列语句
tokenPtr = Strtok(string," ");
第一个参数是要搜索的字符串;strtok的第二个参数””表示string中的标记用空格分开。
函数strtok搜索string中不是分隔符(空格)的第一个字符,这是第一个标记的开头。然后函数寻找字符串中的下一个分隔符,将其换成'\0'字符,这是当前标记的终点。注意标记的开始与结束。
函数strtok保存string中标记后面的下一个字符的指针,并返回当前标记的指针。这样tokenPtr赋值为指向string中第一个标记;
后面再调用strtok时,第一个参数为NULL,继续将string标记化。NULL参数表示调用strtok继续从string中上次调用strtok时保存的位置开始标记化。
#include <stdio.h>
#include <string.h>
int main()
{
char sentence[] = "This is a sentence with 7 tokens";
printf("The string to be tokenized is:%s\n", sentence);
printf("\n\nThe tokens are:\n\n");
char *tokenPtr = strtok(sentence, " ");
while(tokenPtr != NULL) {
printf("%s\n", tokenPtr);
tokenPtr = strtok(NULL," ");
}
printf("After strtok, sentence = %s\n", sentence);
return 0;
}
$ gcc -o str7 str7.c
$ ./str7
The string to be tokenized is:This is a sentence with 7 tokens
The tokens are:
This
is
a
sentence
with
7
tokens
After strtok, sentence = This
参考
http://www.cnblogs.com/lixiaohui-ambition/archive/2012/07/18/2598042.html
http://blog.chinaunix.net/uid-11861796-id-2813603.html