【问题标题】:split string into array by delemiter (Arduino)通过分隔符将字符串拆分为数组(Arduino)
【发布时间】:2016-05-08 15:47:06
【问题描述】:

我正在尝试通过“;”将字符串拆分为 char 数组。

所以是这样的:

String a = "banana;apple;orange";
char *fruits = a.split(";");

我需要做什么才能实现这一目标?

【问题讨论】:

  • 这是 Java 还是 C 语言?
  • @CConard96 也许两者都不是......
  • 语言标签太多——我觉得有必要投票关闭它,因为它太宽泛了。
  • this question 可能会有所帮助
  • @LoganKulinski: 1) 没有语言 C/C++,只有两种**不同的语言 C 和 C++。 2) Arduino 绝对不是 C,3) 也不完全是 C++。

标签: split arduino


【解决方案1】:

我们可以在 C 语言中用strtok() 和一个特定的分隔符(“;”)分割一个字符串。 strtok() 使用该字符串,因此我们必须进行复制。如果其他地方需要原始字符串,则使用字符串的副本而不是原始字符串。

#include <assert.h>
#include <stddef.h>
#include <memory.h>
#include <stdlib.h>
#include <stdio.h>

#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** tokens;
    char months[] = "banana;apple;orange";

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

    tokens = str_split(months, ';');

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

    return 0;
}

测试

splitstr
fruits=[banana;apple;orange]

fruits=[banana]
fruits=[apple]
fruits=[orange]

Process finished with exit code 0

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-29
    • 1970-01-01
    相关资源
    最近更新 更多