C語言的字串分割

來源:互聯網
上載者:User

說起來很有意思,自認為對C語言理解得還是比較深刻的。但居然到今天才知道有個strtok函數,試用了一下突然感慨以前做了多少重複勞動。每次需要解析設定檔,每次需要分割字串,居然都是自己去分割字串,既累人又容易出錯。感概繼續學得不夠全面啊!這裡引用一段strtok用法:

The strtok() function returns a pointer to the next "token" in str1, where str2 contains the delimiters that determine the token. strtok() returns NULL if no token is found. In order to convert a string to tokens, the first call to strtok() should have str1 point to the string to be tokenized. All calls after this should have str1 beNULL.

For 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"
這個函數跟編譯器中的詞法分析很向,在以後的文本處理中,會解決很多問題。看來我有必要系統的學習下C的庫函數,而不僅僅是死紮在文法和一些演算法技巧上面。這樣在平常的工作中才能事半功倍。
使用這個函數,形如下面得設定檔就非常容易解析:
id1 value1 value2 value3
id2 value1 value2 value3
...
使用這個函數,分割字串就更加方便了,例如下面待分割的字串:
12|2345|asld|alsfalskd
只要讀取待處理的資料,然後調用四次strtok就能夠解析出每行的值,以前我一般不是自己解析就是用sscanf,但是strtok更加合適,也更加啊靈活!
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.