【问题标题】:why is strcmp not working in c? [duplicate]为什么 strcmp 在 c 中不起作用? [复制]
【发布时间】:2017-07-08 19:42:55
【问题描述】:

我刚开始学习 c,我想尝试 strcmp 函数,但如果我运行它,它总是给我结果“1”。我输入什么字符串都没有关系。由于第一个字符串比第二个字符串短,所以我希望结果是“-1”。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>



int main()
{
char array1[]="na";
char array2[]="kskkjnkjnknjd";
int i;

i= strcmp(array1,array2);

printf(" %d", i);

    return 0;
}

我也已经尝试摆脱 i 变量,只写“printf(” %d", strcmp(array1, array2)); 并将 %d 替换为 %u,但也不起作用。我我已经在网上搜索并尝试自己弄清楚,可能只是一个简单的错误,如果有人可以提供帮助,我会很高兴。:)

【问题讨论】:

  • 它不只是比较长度。它进行逐个字符的比较,kn 之前。
  • 如果 s1 指向的字符串大于、等于或分别小于 s2 所指向的字符串。您必须比较结果为==0&lt;0&gt;0
  • 如果你想直接比较字符串长度:if (strlen(a) &lt; strlen(b)) puts("-1");

标签: c function strcmp


【解决方案1】:

libc 中的strcmp 几乎总是使用以下等价物进行编码:

int strcmp(char *s1, char *s2)
{
    for(; *s1 && *s2; s1++, s2++)
    {
        int res = *s1-*s2;
        if (res)
            return res;
    }
    return *s1-*s2;
}

它返回第一个不同的比较字符之间的差异,这确保结果符合两个字符串关系==&lt;&gt;

当字符串长度不同时,返回的是较短字符串的\0 字符串结尾与另一个字符串的位置对应字符之间的差。所以结果也应该反映长度差异。

不要指望 0、1 和 -1。

【讨论】:

    【解决方案2】:

    看看这个小程序,它的结构有点像你自己的程序。

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    int main(void)
    {
      char array1[]="a";
      char array2[]="b";
      int i;
    
      i = strcmp(array1,array2);
    
      printf(" %d\n", i);
    
      return 0;
    }
    

    编译并运行它,它返回一个负整数。 (它在我的 gcc 盒子上返回 -1。)

    这是因为“strcmp 函数根据 s1 指向的对象是小于、等于还是大于 s2 指向的对象返回负整数、零整数或正整数。”

    【讨论】:

    • 好吧,我只是误解了函数本身。非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-07-17
    • 1970-01-01
    • 1970-01-01
    • 2015-12-08
    • 1970-01-01
    • 2014-04-29
    • 1970-01-01
    相关资源
    最近更新 更多