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.   
  3.    result is "now "  
  4.    result is " is the time for all "  
  5.    result is " good men to come to the "  
  6.    result is " aid of their country" 
 這個函數跟編譯器中的詞法分析很像,在以后的文本處理中,會解決很多問題。看來我有必要系統的學習下C的庫函數,而不僅僅是死扎在語法和一些算法技巧上面。這樣在平常的工作中才能事半功倍。
使用這個函數,形如下面的配置文件就非常容易解析:
id1 value1 value2 value3
id2 value1 value2 value3
...
    使用這個函數,分割字符串就更加方便了,例如下面待分割的字符串:
12|2345|asld|alsfalskd
        只要讀取待處理的數據,然后調用四次strtok就能夠解析出每行的值,以前我一般不是自己解析就是用sscanf,但是strtok更加合適,也更加啊靈活!

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM