c - str 拆分功能不起作用

标签 c string

我有这个函数可以将一维数组转换为二维数组。当我转换它时,我需要在每个 4x4 正方形之间保留一个 \n(换行符)。

int     count_words(const char *str, char c)
{
    int     i;
    int     count;

    i = 0;
    count = 0;
    while (str[i])
    {
        while (str[i] && str[i] == c)
            i++;
        if (str[i])
        {
            count++;
            while (str[i] && str[i] != c)
                i++;
        }
    }
    return (count);
}

char    *get_word(const char *str, char c)
{
    char    *word;
    int     i;

    i = 0;
    word = (char*)malloc(sizeof(char) * 500);
    while (str[i] && str[i] != c)
    {
        word[i] = str[i];
        i++;
    }
    word[i] = '\0';
    return (word);
}

char    **ft_strsplit(const char *s, char c)
{
    char    **split;
    int     words;
    int     i;

    i = 0;
    words = count_words(s, c);
    split = (char**)malloc(sizeof(char*) * words + 1);
    if (split == NULL)
        return (NULL);
    while (*s)
    {
        if (*s == c)
            s++;
        if (*s)
        {

            if (*s == c)
            {
                split[i] = ft_strdup("\0");
                s++;
                //printf("=========>%s\n", split[i]);
                i++;
            }
            else{
                split[i] = get_word(s, c);
                s = s + ft_strlen(split[i]);

        //printf("%s\n", split[i]);
            i++;}
        }
    }
    split[i] = NULL;
    int  k = 0;
    while (split[k])
    {
        printf("%s\n", split[k]);
        k++;
    }
    return (split);
}

这是输入文件: enter image description here

这是在这个一维字符串中转换的(const char *s):

#...\n#...\n#...\n#...\n\n.#..\n.#..\n.#..\n .#..\n\n###.\n..#.\n....\n....\n\n....\n....\n....\n####\n

这是输出,其中包含随机的非字符。

#...
#...
#...
#...

.#..
.#..
.#..
.#..
�P@��
###.
..#.
....
....

....
....
....
####

为什么会出现随机字符?

最佳答案

实际上,如果我运行您的代码(使用 \n 作为中断字符),它运行良好。

大量的单词内存(虽然没有坏处)。你可以这样做:

    i = 0;
    while (str[i] && str[i] != c) i++;

    word = malloc(i + 1);
    for (int j=0; j<i; j++) word[j]= str[j];
    word[j] = '\0';

关于c - str 拆分功能不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42178098/

相关文章:

c++ - 在 C++ 中以 'D' 作为指数前缀读取双科学记数法

c - 数组的选择排序结构问题

c - 取消引用另一个不兼容类型的指针的别名

c - 无法将结构数组传递给 C 中的函数

php - 如何在 PHP 中将单词转换为数字?

PHP按多个条件自定义排序字符串数组

c - 为什么“while(!feof(file))”总是错误的?

c - 读写位置之间的距离对缓存性能有影响吗?

Python - 水平打印两个字符串,带有 |

c - 将 char 附加到 C 字符串