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]);
}

 

posted @ 2021-06-21 15:50  429512065  阅读(2249)  评论(0编辑  收藏  举报