C語言的字串分割

2021-08-21 15:23:47 字數 1003 閱讀 1670

c語言的字串分割

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

str2nullstr1

str1

for example:

char

="now # is the time for all # good men to come to the # aid of their country"

;char

="#"

;char*=

null;=(

,);while(!=

null

)the above code will display the following output:

is"now "

is" is the time for all "

is" good men to come to the "

is" aid of their country"

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

C語言 strtok 字串分割

參考 c 字串分割方法 實現split 使用函式strtok可實現c語言環境下的字串分割 cstring strtok 函式 char strtok char str,const char delimiters 引數 功能 分割字串 例程 include include include int ma...

C 字串分割

c 中的字元分割是乙個常見的應用,下面是乙個字串分割的 字串分割 vectorsplit string const string str,const string delimiters else pos delim split str.find delimiters res.push back sp...

字串分割 C

經常碰到字串分割的問題,這裡總結下,也方便我以後使用。一 用strtok 函式進行字串分割 原型 char strtok char str,const char delim 功能 分解字串為一組字串。引數說明 str為要分解的字串,delim為分隔符字串。返回值 從str開頭開始的乙個個被分割的串。...