c - 递归函数比较没有库函数的字符串

标签 c string function recursion

我应该用 C 编程语言编写一个递归函数,检查字符串 1 是否大于等于或小于字符串 2,从而返回 10, -1 分别。

下面是我编写的代码。该程序无法终止,我无法找出原因。请给我一些建议。谢谢。

int revisedStrcmp(char *s1, char *s2) {
    int i = 0, n = 0, p = 0;

    if (s1[i] == '\0' && s2[i] != '\0') //s1 shorter than s2
        return -1;

    else if (s1[i] != '\0' && s2[i] == '\0') //s1 longer than s2
        return 1;

    else if (s1[i] != '\0' && s2[i] != '\0')  //both not equal to null
    {
        if (s1[i] > s2[i])  n += 1; //s1
        else if (s1[i] < s2[i]) p += 1; //s2
        else
        {
           n += 1; //s1
           p += 1; //s2
        }
        i += 1;
        return revisedStrcmp(s1, s2);
    }
    else    //if s1[i] & s2[i] are null
    {
        if (n > p) //s1 > s2
            return 1;
        else if (n < p)
            return -1;
        else
            return 0;
    }
}

最佳答案

您的函数中的主要问题是您没有在对 revisedStrcmp 的递归调用中传递更新的指针,从而导致无限循环和潜在的堆栈溢出

这是一个更正和简化的版本:

int revisedStrcmp(const char *s1, const char *s2) {
    if (*s1 < *s2)
        return -1;
    if (*s1 > *s2)
        return +1;
    // *s1 == *s2
    if (*s1 == '\0')
        return 0;
    return revisedStrcmp(s1 + 1, s2 + 1);
}

不需要为较短的字符串做特殊情况,因为可以在比较中使用空终止符。

这种特殊的递归风格称为尾递归,现代编译器会将其编译成循环。

但是请注意,要使 revisedStrcmp() 返回与 strcmp 相同的顺序,必须对 unsigned char 值执行比较,而不是plain char,可以在许多架构上默认签名:

int revisedStrcmp(const char *s1, const char *s2) {
    unsigned char c1 = *s1, c2 = *s2;
    if (c1 < c2)
        return -1;
    if (c1 > c2)
        return +1;
    // c1 == c2
    if (c1 == '\0')
        return 0;
    return revisedStrcmp(s1 + 1, s2 + 1);
}

关于c - 递归函数比较没有库函数的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54959848/

相关文章:

javascript - 使用回调函数传递参数

c - 什么时候未定义的行为可以被认为是众所周知的并被接受?

C++ 字符串到 C 字符串

c# - 拆分字符串模式

java - 从字符串中获取不同的字符

R包创建函数名称和.R/.rd名称

c - BST、后继者、代码问题

c++ - USB 大容量存储 linux

c - 为什么C程序崩溃?

javascript - 有没有办法在javascript中做到这一点?