c - 拆分字符串中的空格并将它们存储在没有库的C中的表中

标签 c string malloc

上周我的类(class)有一个作业,我必须用空格、制表符和 \n 作为分隔符来拆分一个字符串,并将每个“单词”存储在一个数组中。我想我已经很接近了,但我的输出很奇怪,所以如果有人能告诉我我忘记了什么,那就太好了。唯一的问题是我只能使用 malloc

char    **ft_split_whitespaces(char *str)
{
    int     i;
    int     j;
    int     k;
    char    **tab;

    i = 0;
    j = 0;
    k = 0;
    tab = (char**)malloc(sizeof(*tab) * (ft_nb_words(str) + 1));
    while (str[i])
    {
        while (str[i] == ' ' || str[i] == '\t' || str[i] == '\n')
            i++;
        if (str[i])
        {
            if ((tab[j] = (char*)malloc(sizeof(char) * (ft_len_word(str + i) + 1))) == NULL)
                return (NULL);
            while (k < ft_len_word(str + i))
                tab[j][k++] = str[i++];
            tab[j++][k] = '\0';
            k = 0;
        }
    }
    tab[j] = NULL;
    return (tab);
}

返回单词长度和单词数量的函数工作正常,所以我认为问题出在 main 函数上。

最佳答案

如果你用一个指针指向最后一次出现的特定字符('' '\n'\t),这就很容易处理了。

   char    **ft_split_whitespaces(char *str)
    {
    int     i;
    int     j;
    int     k;
    char    **tab;
    char *prevToken=str;

    i = 0;
    j = 0;
    k = 0;
    tab = (char**)malloc(sizeof(*tab) * (ft_nb_words(str) + 1));
    while (str[i] != '\0')
    {

        if(str[i] == ' ' || str[i] == '\t' || str[i] == '\n')
        {
            i++;
            if ((tab[j] = (char*)malloc(sizeof(char) * (ft_len_word(prevToken) + 1))) == NULL)
                return (NULL);

            while (k < ft_len_word(prevToken) &&
                (prevToken[k] !=' ' &&  prevToken[k] != '\t' &&  prevToken[k] != '\n'))
                tab[j][k] = prevToken[k++];

            printf("tab=%s\n", tab[j]);
            k = 0;
            j++;
            prevToken=(str+i);
        }
        else{
           i++;
         }
    }

      /* to handle the last word */
            if ((tab[j] = (char*)malloc(sizeof(char) * (ft_len_word(prevToken) + 1))) == NULL)
                return (NULL);

            while (k < ft_len_word(prevToken) &&
                (prevToken[k] !=' ' &&  prevToken[k] != '\t' &&  prevToken[k] != '\n'))
                tab[j][k] = prevToken[k++];
            printf("tab=%s\n", tab[j]);


    tab[j] = NULL;
    return (tab);
    }

关于c - 拆分字符串中的空格并将它们存储在没有库的C中的表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51740149/

相关文章:

c - 在 XCode 中为模拟器编译内联 asm 但无法为设备编译

c - C中的目录问题

c++ - 替换 std::string 中字符的最快(也是最安全)方法

python - 从数据提取中删除字母只留下数字Python

c - free() 没有正确释放内存?

c - 如何将字符串保存在动态二维数组中?

c - 使用指向结构的指针丢失内存字节

在 C 中计算时间跨度

C++ 原型(prototype)与实现不同

正则表达式 - 字符串帮助 - Stata