C语言的字符串分割

源:C语言的字符串分割

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 );  
   }              
  1. The above code will display the following output:
  2. result is "now "
  3. result is " is the time for all "
  4. result is " good men to come to the "
  5. result is " aid of their country"
 这个函数跟编译器中的词法分析很像,在以后的文本处理中,会解决很多问题。看来我有必要系统的学习下C的库函数,而不仅仅是死扎在语法和一些算法技巧上面。这样在平常的工作中才能事半功倍。
使用这个函数,形如下面的配置文件就非常容易解析:
id1 value1 value2 value3
id2 value1 value2 value3
...
    使用这个函数,分割字符串就更加方便了,例如下面待分割的字符串:
12|2345|asld|alsfalskd
        只要读取待处理的数据,然后调用四次strtok就能够解析出每行的值,以前我一般不是自己解析就是用sscanf,但是strtok更加合适,也更加啊灵活!