您的位置:首页 > 编程语言 > C语言/C++

c语言实现字符串分割

2013-06-23 16:06 429 查看
用到c函数库的strtok()

先上个例子,显示效果

example:
   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 );
   }            

The above code will display the following output:

   result is "now "
   result is " is the time for all "
   result is " good men to come to the "
   result is " aid of their country"


 

说明:strtok(char s[], const char *delim)用来将字符串分割成一个个片段。参数s指向欲分割的字符串,参数delim则为分割字符串中包含的所有字符。当strtok()在参数s的字符串中发现参数delim中包涵的分割字符时,则会将该字符改为\0 字符。在第一次调用时,strtok()必需给予参数s字符串往后的调用则将参数s设置成NULL。每次调用成功则返回指向被分割出片段的指针。
 
strtok() 函数里面有个static变量str 记录了第一次调用strtok()函数输入参数的余串,所以第一次调用时[b]strtok()必需给予参数s字符串往后的调用则将参数s设置成NULL,当参数str为NULL时函数对余串进行处理。

[/b]
原文链接:http://www.cnblogs.com/linxr/archive/2011/12/28/2304350.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: