首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C语言 >

求strtok的解释解决方案

2012-04-08 
求strtok的解释没有用过这个函数,看不懂怎么回事?英语学的也不好:msdn上的:Returns a pointer to the next

求strtok的解释
没有用过这个函数,看不懂怎么回事?英语学的也不好:

msdn上的:Returns a pointer to the next token found in strToken. They return NULL when no more tokens are found. Each call modifies strToken by substituting a NULL character for each delimiter that is encountered.

尤其是最后一句,没有看懂


C/C++ code
// crt_strtok.c// compile with: /W1// 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;int main( void ){   printf( "Tokens:\n" );    // Establish string and get the first token:   token = strtok( string, seps ); // C4996   // Note: strtok is deprecated; consider using strtok_s instead   while( token != NULL )   {      // While there are tokens in "string"      printf( " %s\n", token );      // Get next token:       token = strtok( NULL, seps ); // C4996   这里为什么可以置空??置空后怎么知道要在string中寻找?   }}---------------------Tokens: A string of tokens and some more tokens


[解决办法]
#include <string.h>
char *strtok( char *str1, const char *str2 );


功能:函数返回字符串str1中紧接“标记”的部分的指针, 字符串str2是作为标记的分隔符。如果分隔标记没有找到,函数返回NULL。

为了将字符串转换成标记,第一次调用str1 指向作为标记的分隔符。之后所以的调用str1 都应为NULL。


C/C++ code
int   main() {   char str[] = "now # is the time for all # good men to come to the # aid of their country";  char delims[] = "#";  char *result = NULL;  result = strtok( str, delims );    while( result != NULL )  {      printf( "result is \"%s\"\n", result );      result = strtok( NULL, delims );  }}
[解决办法]
char *strtok(char *s1, const char *s2)

该函数将s1中首次出现s2中字符的位置置为NULL,因此会破坏s1字符串。该函数一般用于分解s1字符串为用特定分隔符分隔的多个字符串,s2一般设置为s1中的分隔字符,比如空格,逗号等,例如将一条自然英文语句分解为单词。

首次调用strtok(s1, s2)
返回指向s2截断的第一个字符串
再调用strtok(NULL, s2)
返回接下来的由s2截断的字符串
依次……

热点排行