C - 在空格处拆分字符串

时间:2017-08-17 16:04:02

标签: c split

我需要在有空格的地方拆分一个字符串(ex string:Hello this is an example string.到一个单词数组。我不确定我在这里缺少什么,我也很好奇什么是最好的测试此函数的方法是。允许的唯一库函数是malloc

感谢任何帮助!

#include <stdlib.h>

char **ft_split(char *str) {
    int wordlength;
    int wordcount;
    char **wordbank;
    int i;
    int current;

    current = 0;
    wordlength = 0;
    //while sentence
    while (str[wordlength] != '\0') {
        //go till letters
        while (str[current] == ' ')
            current++;
        //go till spaces
        wordlength = 0;
        while (str[wordlength] != ' ' && str[wordlength] != '\0')
            wordlength++;
         //make memory for word
        wordbank[wordcount] = malloc(sizeof(char) * (wordlength - current + 1));

        i = 0;
        //fill wordbank current
        while (i < wordlength - current) {
            wordbank[wordcount][i] = str[current];
            i++;
            current++;
        }

        //end word with '\0'
        wordbank[wordcount][i] = '\0';

        wordcount++;
    }
    return wordbank;
}

2 个答案:

答案 0 :(得分:1)

你也需要malloc() wordbank。您可以计算单词的数量,然后

wordbank = malloc((count + 1) * sizeof(*wordbank));
if (wordbank == NULL)
    return NULL;

注意:根据定义,sizeof(char)为1。 sizeof *pointer总是你想要的。

答案 1 :(得分:1)

您的代码中存在多个问题:

  • 您没有为wordbank分配数组指向,取消引用未初始化的指针具有未定义的行为。
  • 您扫描字符串的方法已损坏:您在循环内重置wordlength,以便继续从字符串的开头重新扫描。
  • 您应该在数组中为尾随空指针分配一个额外的条目,以向调用者指示数组的结尾。

以下是修改后的版本:

#include <stdlib.h>

char **ft_split(const char *str) {
    size_t i, j, k, wordcount;
    char **wordbank;

    // count the number of words:
    wordcount = 0; 
    for (i = 0; str[i]; i++) {
        if (str[i] != ' ' && (i == 0 || str[i - 1] == ' ')) {
            wordcount++;
        }
    }

    // allocate the word array
    wordbank = malloc((wordcount + 1) * sizeof(*wordbank));
    if (wordbank) {
        for (i = k = 0;;) {
            // skip spaces
            while (str[i] == ' ')
                i++;
            // check for end of string
            if (str[i] == '\0')
                break;
            // scan for end of word
            for (j = i++; str[i] != '\0' && str[i] != ' '; i++)
                continue;
            // allocate space for word copy
            wordbank[k] = p = malloc(i - j + 1);
            if (p == NULL) {
                // allocation failed: free and return NULL
                while (k-- > 0) {
                    free(wordbank[k]);
                }
                free(wordbank);
                return NULL;
            }
            // copy string contents
            memcpy(p, str + j, i - j);
            p[i - j] = '\0';
        }
        // set a null pointer at the end of the array
        wordbank[k] = NULL;
    }
    return wordbank;
}