淺談C語言的字符串分割
說起來很有意思,自認(rèn)為對C語言理解得還是比較深刻的。但居然到今天才知道有個strtok函數(shù),試用了一下突然感慨以前做了多少重復(fù)勞動。每次需要解析配置文件,每次需要分割字符串,居然都是自己去分割字符串,既累人又容易出錯。感概技術(shù)學(xué)得不夠全面?。∵@里引用一段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 be NULL.
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 ); } /* 何問起 hovertree.com */
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"
這個函數(shù)跟編譯器中的詞法分析很像,在以后的文本處理中,會解決很多問題??磥砦矣斜匾到y(tǒng)的學(xué)習(xí)下C的庫函數(shù),而不僅僅是死扎在語法和一些算法技巧上面。這樣在平常的工作中才能事半功倍。
使用這個函數(shù),形如下面的配置文件就非常容易解析:
id1 value1 value2 value3
id2 value1 value2 value3
...
使用這個函數(shù),分割字符串就更加方便了,例如下面待分割的字符串:
12|2345|asld|alsfalskd
只要讀取待處理的數(shù)據(jù),然后調(diào)用四次strtok就能夠解析出每行的值,以前我一般不是自己解析就是用sscanf,但是strtok更加合適,也更加啊靈活!
以上這篇淺談C語言的字符串分割就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
Qt使用SQLite數(shù)據(jù)庫實現(xiàn)數(shù)據(jù)增刪改查
這篇文章主要為大家詳細(xì)介紹了Qt如何使用SQLite數(shù)據(jù)庫實現(xiàn)數(shù)據(jù)增刪改查功能,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起了解一下2023-06-06C/C++寬窄字符轉(zhuǎn)換與輸出的多種實現(xiàn)方法
本文主要介紹了C/C++寬窄字符轉(zhuǎn)換與輸出的多種實現(xiàn)方法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-08-08詳解C/C++實現(xiàn)各種字符轉(zhuǎn)換方法合集
這篇文章主要為大家詳細(xì)介紹了C/C++中實現(xiàn)各種字符轉(zhuǎn)換的方法,文中的示例代碼講解詳細(xì),對我們學(xué)習(xí)C++具有一定借鑒價值,需要的可以參考一下2022-09-09C++實現(xiàn)LeetCode(77.Combinations 組合項)
這篇文章主要介紹了C++實現(xiàn)LeetCode(Combinations 組合項),本篇文章通過簡要的案例,講解了該項技術(shù)的了解與使用,以下就是詳細(xì)內(nèi)容,需要的朋友可以參考下2021-07-07