不知道如何将我的函数中的行数减少到 25 行

Can't figure out how to reduce the amount of lines in my function to 25

提问人:pclaus 提问时间:11/5/2023 最后编辑:pclaus 更新时间:11/5/2023 访问量:62

问:

我正在用 C 语言制作自己的拆分函数版本,但每个函数只能有 25 行代码。我被困住了,我不知道如何解决这个问题。

我尝试通过创建单独的函数来解决问题,但这些函数有 5 个参数,限制为 4 个。就像在单独的行上声明变量并在变量后面有一个换行符一样。

有谁知道如何将拆分函数更改为 25 行或更少?

char    **ft_split(char const *s, char c)
{
        int             index;
        char    **strings;
        size_t  i;
        size_t  j;

        index = -1;
        i = 0;
        j = 0;
        strings = malloc((number_of_substrings(s, c) + 1) * sizeof(char *));
        if (!s || !strings)
                return (0);
        while (i <= ft_strlen(s))
        {
                if (s[i] != c && index < 0)
                        index = i;
                else if ((s[i] == c || i == ft_strlen(s)) && index >= 0)
                {
                        if ((strings[j] = copy_word(s, index, i)) == 0)
                        {
                                cleanup_strings(strings, j);
                                return (NULL);
                        }
                        j++;
                        index = -1;
                }
                i++;
        }
        strings[j] = 0;
        return (strings);
}

这些是我在函数中使用的其他函数:

static int      number_of_substrings(char const *s, char c)
{
        int     index;
        int     count;

        index = 0;
        count = 0;
        while (*s)
        {
                if (*s != c && count == 0)
                {
                        count = 1;
                        index++;
                }
                else if (*s == c)
                        count = 0;
                s++;
        }
        return (index);
}

static char     *copy_word(const char *s, int start, int finish)
{
        int             index;
        char    *substring;

        index = 0;
        substring = malloc((finish - start + 1) * sizeof(char));
        if (!substring)
                return (NULL);
        while (start < finish)
                substring[index++] = s[start++];
        substring[index] = '\0';
        return (substring);
}

void    cleanup_strings(char **strings, size_t j)
{
    while (j > 0)
    {
        j--;
        free(strings[j]);
    }
    free(strings);
}
C 函数

评论

0赞 Weather Vane 11/5/2023
int index = -1; size_t i = 0, j = 0;在两条线上会缩短几行。
1赞 Weather Vane 11/5/2023
从编辑:是否有一种特殊的需求告诉你使用台词,然后告诉你不要使用太多?要求在函数开始时声明所有变量是过时的。
0赞 pclaus 11/5/2023
是的,我需要遵循一个“规范”。一些规则是,一个函数不能超过 25 行,并且每个变量都需要在新行上声明。Split 是一个函数,它接受一个字符串并拆分为该字符串中各个单词的数组。
2赞 Shawn 11/5/2023
函数应该足够短,以便相当容易理解和理解,但对行数的任意限制似乎特别愚蠢。
0赞 Shawn 11/5/2023
(将代码格式样式切换为一个真大括号将减少一些行)

答: 暂无答案