将String拆分成单词

时间:2013-11-21 00:32:38

标签: c arrays string split

我有一个长文本作为字符串,我想用C将它分成单个单词。 我尝试使用strtok()解决方案,但这对我来说感觉就像一个肮脏的解决方案,所有的指针疯狂。 是否有直接的解决方案将字符串拆分为单词并将其存储在数组中?

我想到了一个for循环,迭代字符串并在出现空格或句号时启动一个新的“计数器”,但是当它存储它时我总是感到困惑......

希望你能帮助我

1 个答案:

答案 0 :(得分:1)

也许你可以像这样处理字符串。这只是一个简单的演示。因此,在将代码投入实际使用之前,您可能需要优化代码。

#define skip_white_space(p)               \
    do {                                  \
        while (*p != '\0' && isspace(*p)) \
            ++p;                          \
    } while (0)

#define skip_non_space(p)                  \
    do {                                   \
        while (*p != '\0' && !isspace(*p)) \
            ++p;                           \
    } while (0)

#define WORD_MAXLEN 64

char **strsplit(char *text, int *nword)
{
    char *p, *q, **words;

    words = NULL;
    *nword = 0;

    p = text;
    while (*p != '\0') {
        skip_white_space(p);
        q = p;
        skip_non_space(p);
        if (p > q) {
            ++*nword;
            words = (char **)realloc(words, *nword * sizeof(*words));
            words[*nword - 1] = (char *)malloc(WORD_MAXLEN);
            strncpy(words[*nword - 1], q, p - q);
            words[*nword - 1][p - q] = '\0';
        }
        skip_white_space(p);
    }

    return words;
}
相关问题