C语言分割字符串函数strtok!
在编程过程中,有时需要对字符串进行分割.而有效使用这些字符串分隔函数将会给我们带来很多的便利.
下面我将在msdn中学到的strtok函数做如下翻译.
strtok :
在一个字符串查找下一个符号
char *strtok( char *strtoken, const char *strdelimit );
返回值:
返回指向在strtoken字符串找到的下一个符号的指针,当在字符串找不到符号时,将返回null.每
次调用都通过用null字符替代在strtoken字符串遇到的分隔符来修改strtoken字符串.
参数:
strtoken:包含符号的字符串
strdelimit:分隔符集合
注:第一次调用strtok函数时,这个函数将忽略间距分隔符并返回指向在strtoken字符串找到的第一个符
号的指针,该符号后以null字符结尾.通过调用一系列的strtok函数,更多的符号将从strtoken字符串中分
离出来.每次调用strtok函数时,都将通过在找到的符号后插入一个null字符来修改strtoken字符串.为了
读取strtoken中的下一个符号,调用strtok函数时strtoken参数为null,这会引发strtok函数在已修改过
的strtoken字符串查找下一个符号.
example(摘自msdn)
点击(此处)折叠或打开
- /* strtok.c: in this program, a loop uses strtok
- * to print all the tokens (separated by commas
- * or blanks) in the string named "string".
- */
- #include <string.h>
- #include <stdio.h>
- char string[] = "a string\tof ,,tokens\nand some more tokens";
- char seps[] = " ,\t\n";
- char *token;
- void main( void )
- {
- printf( "%s\n\ntokens:\n", string );
- /* establish string and get the first token: */
- token = strtok( string, seps );
- while( token != NULL )
- {
- /* while there are tokens in "string" */
- printf( " %s\n", token );
- /* get next token: */
- token = strtok( NULL, seps );
- }
- }
输出结果:
a string of ,,tokens
and some more tokens
and some more tokens
tokens:
a
string
of
tokens
and
some
more
tokens