淺談C說話的字符串朋分。本站提示廣大學習愛好者:(淺談C說話的字符串朋分)文章只能為提供參考,不一定能成為您想要的結果。以下是淺談C說話的字符串朋分正文
說起來很成心思,自以為對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 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"
這個函數跟編譯器中的詞法剖析很像,在今後的文本處置中,會處理許多成績。看來我有需要體系的進修下C的庫函數,而不只僅是逝世扎在語法和一些算法技能下面。如許在平凡的任務中能力事半功倍。
應用這個函數,形以下面的設置裝備擺設文件就異常輕易解析:
id1 value1 value2 value3
id2 value1 value2 value3
...
應用這個函數,朋分字符串就加倍便利了,例以下面待朋分的字符串:
12|2345|asld|alsfalskd
只需讀取待處置的數據,然後挪用四次strtok就可以夠解析出每行的值,之前我普通不是本身解析就是用sscanf,然則strtok加倍適合,也加倍啊靈巧!
以上這篇淺談C說話的字符串朋分就是小編分享給年夜家的全體內容了,願望能給年夜家一個參考,也願望年夜家多多支撐。