C語言按指定分隔符拆分字符串


 

C語言按指定分隔符拆分字符串

1. 先看下面的函數

參數1:分隔符、

參數2:字符串

參數3:分割后的字符串存放的位置

參數4:預計需要分割的個數

int at_get_words(char chop,char *srcStr, char **word, int size) { int index = 0; int i = 0; char *str = srcStr; while (*(str + i) != '\0') { if (*(str + i) == chop) {
            word[index] = str; word[index++][i] = '\0'; str = (str + i + 1); i = -1; } if (*(str + i) == '\r') { word[index] = str; word[index++][i] = '\0'; str = (str + i); i = 0; break; } if (index >= size) { return index; } i++; } if (strlen(str) > 0) { word[index++] = str; } return index; }

2. 使用方法

char *words[5] = { NULL }; char buf[64] = "115200, 8, 1, NONE, NFC"; if (at_get_words(',',buf,words,5 ) == 5) { printf("out 0:%s",word[0]); printf("out 1:%s",word[1]); printf("out 2:%s",word[2]); printf("out 3:%s",word[3]); printf("out 4:%s",word[4]); }

 


免責聲明!

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



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