c - C 中使用分隔符分割字符串

标签 c string split

如何在 C 编程语言中编写一个函数来拆分并返回带有分隔符的字符串数组?

char* str = "JAN,FEB,MAR,APR,MAY,JUN,JUL,AUG,SEP,OCT,NOV,DEC";
str_split(str,',');

最佳答案

您可以使用strtok()分割字符串的函数(并指定要使用的分隔符)。请注意,strtok() 将修改传递给它的字符串。如果其他地方需要原始字符串,请复制它并将该副本传递给 strtok()

编辑:

示例(请注意,它不处理连续的分隔符,例如“JAN,,,FEB,MAR”):

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>

char** str_split(char* a_str, const char a_delim)
{
    char** result    = 0;
    size_t count     = 0;
    char* tmp        = a_str;
    char* last_comma = 0;
    char delim[2];
    delim[0] = a_delim;
    delim[1] = 0;

    /* Count how many elements will be extracted. */
    while (*tmp)
    {
        if (a_delim == *tmp)
        {
            count++;
            last_comma = tmp;
        }
        tmp++;
    }

    /* Add space for trailing token. */
    count += last_comma < (a_str + strlen(a_str) - 1);

    /* Add space for terminating null string so caller
       knows where the list of returned strings ends. */
    count++;

    result = malloc(sizeof(char*) * count);

    if (result)
    {
        size_t idx  = 0;
        char* token = strtok(a_str, delim);

        while (token)
        {
            assert(idx < count);
            *(result + idx++) = strdup(token);
            token = strtok(0, delim);
        }
        assert(idx == count - 1);
        *(result + idx) = 0;
    }

    return result;
}

int main()
{
    char months[] = "JAN,FEB,MAR,APR,MAY,JUN,JUL,AUG,SEP,OCT,NOV,DEC";
    char** tokens;

    printf("months=[%s]\n\n", months);

    tokens = str_split(months, ',');

    if (tokens)
    {
        int i;
        for (i = 0; *(tokens + i); i++)
        {
            printf("month=[%s]\n", *(tokens + i));
            free(*(tokens + i));
        }
        printf("\n");
        free(tokens);
    }

    return 0;
}

输出:

$ ./main.exe
months=[JAN,FEB,MAR,APR,MAY,JUN,JUL,AUG,SEP,OCT,NOV,DEC]

month=[JAN]
month=[FEB]
month=[MAR]
month=[APR]
month=[MAY]
month=[JUN]
month=[JUL]
month=[AUG]
month=[SEP]
month=[OCT]
month=[NOV]
month=[DEC]

关于c - C 中使用分隔符分割字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37663953/

相关文章:

c - 在 C 中传递可变数量参数的更紧凑方法

c - #define 指令中的 for 或 while 循环

c - 嵌套循环 Cuda C

c - 不在 if 语句之外打印

c# - 如果在返回字符串的方法中找不到字符串,则返回替代值

python - 将字符串和整数分割为特定长度的python

python - 索引错误 : string index out of range - with len()

.net - 如何使用VB.NET为字符串赋值?

java - 在每 4 个字符处拆分一个字符串?

c - 在 C 中拆分 ASCII 文本文件