gpt4 book ai didi

c - 如何使 strcmp 函数?

转载 作者:太空宇宙 更新时间:2023-11-04 06:56:32 26 4
gpt4 key购买 nike

我想创建自己的 strcmp 函数,就像 C 中的那样。

int my_cmp(const char* str1, const char* str2)  
{
int index;
for (index = 0; str1[index] != '\0' && str2[index] != '\0'; index++)
if (str1[index] != str2[index])
return (str1[index] - str2[index]);
return 0;
}

我说的对吗?我知道并非所有的字符串都具有相同的长度。我不确定 for 语句的条件。

最佳答案

这是 Official implemention 之一.

int strcmp(const char *s1, const char *s2)
{
for ( ; *s1 == *s2; s1++, s2++)
if (*s1 == '\0')
return 0;
return ((*(unsigned char *)s1 < *(unsigned char *)s2) ? -1 : +1);
}

更新:

你的代码问题:

  1. 您的代码对于相同长度的字符串工作正常,其他情况下它会出错。
  2. Extended ASCII (范围在128~255之间),你使用sign char,所以它们的值会溢出为负值,那么你可能会得到一个错误的值。

修复版本:

int my_cmp(const char* str1, const char* str2)  
{
int index;
for (index = 0; str1[index] != '\0' && str2[index] != '\0'; index++)
if (str1[index] != str2[index])
return ((*(unsigned char *)str1 < *(unsigned char *)str2) ? -1 : +1);

// here is the fix code.
if (str1[index] != '\0') {
return 1;
} else if (str2[index] != '\0') {
return -1;
}

return 0;
}

关于c - 如何使 strcmp 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43672982/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com