【问题标题】:strcmp misbehave with 2 same stringsstrcmp 行为不端与 2 个相同的字符串
【发布时间】:2015-09-28 18:24:34
【问题描述】:

我有这个代码:

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

int main() {

  char s1[50], s2[50];

  printf("write s1:\n");
  fgets(s1, sizeof(s1), stdin);

  printf("s2:\n");
  fgets(s2, sizeof(s2), stdin);

  printf("The concatenation of the two strings: %s\n", strcat(s1, s2));

  if( strcmp(s2, s1) < 0 ) {
    printf("s2 is shorter than s1.\n");
  } else if( strcmp(s2, s1) > 0 ) {
    printf("s2 is longer than s1.\n");
  } else {
    printf("strings are equal.\n");
  }

  return 0;
}

问题是,当我写 2 个相同的字符串(如 abc 或其他)时,strcmp 返回“s2 比 s1 短。”

这是正常输出还是我做错了什么?如果有,在哪里?

或者 strcat 使字符串不相等?对此有什么办法吗?

谢谢

【问题讨论】:

  • 参见strcmp 部分返回值。返回的值仅与第一个差异有关(与总长度比较无关)。如果要比较字符串长度,请使用 strlen..
  • 是的。当 strcat 在代码中时,strcmp 返回一个非零数。当我评论它时,strcmp 返回 0
  • s1 = "abcabc" and s2 = "abc",比较使s2比s1短。
  • 所以代码没问题,这应该是正确的答案?

标签: c strcmp


【解决方案1】:

你在做

 strcat(s1, s2)

在比较之前。这将修改字符串s1,因此字符串将不相等

【讨论】:

    【解决方案2】:

    在执行 strcmp 之前,您正在执行 strcat。 strcat 会将 s2 连接到 s1

    【讨论】:

      【解决方案3】:

      Strcmp 根据其内容的值(类似于字典顺序,如果您愿意,但不完全是这样)比较字符串,而不是根据它们的长度。

      例如:“abc”>“abb”

      【讨论】:

        【解决方案4】:

        尝试替换

            printf("The concatenation of the two strings: %s\n", strcat(s1, s2));
        

            printf("The two strings are: '%s' and '%s' and their concatenation: '%s'\n",
            s1, s2, strcat(s1, s2));
        

        然后阅读strcat的描述。

        如果这没有帮助,请将%s 序列替换为%p。 (您可能必须阅读printf 文档中对%p 格式说明符的描述。)

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-01-10
          • 1970-01-01
          • 1970-01-01
          • 2015-10-18
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多