C語言按指定分隔符拆分字串
阿新 • • 發佈:2021-06-21
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]);
}