c语言实现字符串分割

来源:互联网 发布:门店数据分析 编辑:程序博客网 时间:2024/05/21 22:33

用到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()函数输入参数的余串,所以第一次调用时strtok()必需给予参数s字符串往后的调用则将参数s设置成NULL,当参数str为NULL时函数对余串进行处理。

原文链接:http://www.cnblogs.com/linxr/archive/2011/12/28/2304350.html