c - 从 string.h 库复制 strcmp() 函数

标签 c c-strings strcmp function-definition

我正在尝试从 string.h 库中复制 strcmp() 函数,这是我的代码

/**
 * string_compare - this function compares two strings pointed
 * by s1 and s2. Is a replica of the strcmp from the string.h library
 * @s1: The first string to be compared
 * @s2: The second string to be compared
 *
 * Return: On success, it returns:
 * 0 if s1 is equal to s2
 * negative value if s1 is less that s2
 * positive value if s1 is greater than s2
 */

int string_compare(char *s1, char *s2)
{
        int sum = 0, i;

        for (i = 0; s1[i] != '\0' && s2[i] != '\0'; i++)
                sum += (s1[i] - s2[i]);
        for ( ; s1[i] != '\0'; i++)
                sum += (s1[i] - 0);
        for ( ; s2[i] != '\0'; i++)
                sum += (0 - s2[i]);

  

        return (sum);
}

我使用这个示例代码尝试了我的函数:

#include <stdio.h>

int main(void)
{
    char s1[] = "Hello";
    char s2[] = "World!";

    printf("%d\n", string_compare(s1, s2));
    printf("%d\n", string_compare(s2, s1));
    printf("%d\n", string_compare(s1, s1));
    return (0);
}

我得到以下输出,

-53
-500
0

但我应该得到:

-15
15
0

为什么我会得到这样的结果??

最佳答案

这种做法是不正确的。

假设第一个字符串是"B",第二个字符串是"AB"

很明显,第一个字符串在字典顺序上大于第二个字符串。

但是由于这个for循环,结果会是负数

    for ( ; s2[i] != '\0'; i++)
            sum += (0 - s2[i]);

尽管该函数应返回一个正值。

此外,int 类型的变量 sum 可能会发生溢出。

此外,函数至少应声明为

int string_compare( const char *s1, const char *s2);

因为传递的字符串在函数内没有改变。

函数可以这样定义

int string_compare( const char *s1, const char *s2 )
{
    while ( *s1 && *s1 == *s2 )
    {
        ++s1;
        ++s2;
    }

    return ( unsigned char )*s1 - ( unsigned char )*s2;
} 

关于c - 从 string.h 库复制 strcmp() 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73337692/

相关文章:

c - 使用 cbreak() 接收到两位数地址后,直接在数组位置打印数据; <curses.h> 和 getch();

c - 将 0 分配给 %ecx 寄存器

c - 替换 C 中的单词

c - 如何读取字符串直到两个连续的空格?

c++ - 程序在返回 cstring 时返回垃圾值

c - 我的字符串比较结果错误

c - gtk+ 保存文件同时保留 Linux 中的文件权限

自己创建线程

c - strcmp 有什么问题?

c - 在 strtok() -C 的输出上使用 strcmp()