【问题标题】:Compare between two char arrays with different lengths? [closed]比较两个不同长度的字符数组? [关闭]
【发布时间】:2014-01-26 11:05:58
【问题描述】:

有没有办法比较两个不同长度的字符数组?

char_1[10] = "hello";
char_2[256] = "hello";

ret = strcmp(char_1,char_2); 
printf("%d\n", ret);

我没有得到 0

我可以使用任何我想要的库...

谢谢!

【问题讨论】:

  • strcmp 有什么问题?
  • “不做这项工作” - “工作”到底是什么?
  • 提供完整的示例,具有预期的输出。你真的有一个点吗?注意:这是允许的,不是大声的。
  • 命令是 ret = strcmp(char_1,char_2);当我打印 ret 的值时,我没有得到 0
  • 我只是喜欢人们如何忽视 cmets ..... 这对你来说是一个完整的例子吗?工作是什么?你真的有一个点吗?

标签: c string string-comparison


【解决方案1】:

你必须学习:

  • 如何描述你想做什么。
  • 如何提供完整的示例。

所以,你没有提供一个合适的例子。它不编译。它充满了语法错误。这是一个很好的例子:

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

int main() {
    char char_1[10] = "hello";
    char char_2[256] = "hello";

    int ret = strcmp(char_1,char_2);
    printf("%d\n", ret);
}

正如预期的那样输出0

我们不知道你的真实代码是什么,所以我们无法知道你的问题是什么。

【讨论】:

  • 感谢您的评论,我需要从缓冲区中读取一些单词(服务器端)并将其与另一个单词进行比较。缓冲区大小为 256,当我使用 strcmp 时,我没有得到 0,根据此命令,两个单词(字符串)不相等。
  • 我为你感到难过。您甚至无法解释“提供完整示例”之类的简单句子。
【解决方案2】:

以下是strcmp() 函数的声明。

int strcmp(const char *str1, const char *str2)

参数:

str1 -- This is the first string to be compared.

str2 -- This is the second string to be compared.

返回值:

该函数返回值如下:

if Return value if < 0 then it indicates str1 is less than str2

if Return value if > 0 then it indicates str2 is less than str1

if Return value if = 0 then it indicates str1 is equal to str2

strcmp(char_1,char_2);

【讨论】:

    【解决方案3】:

    您的代码是正确的。 strcmp 返回零。看看就好。

    char_1[10]="hello"
    char_2[256]="hello"
    
    ret= strcmp (char_1,char_2); 
    printf("%d\n",ret);
    

    【讨论】:

      猜你喜欢
      • 2013-04-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-17
      • 1970-01-01
      • 1970-01-01
      • 2020-02-04
      • 2021-02-25
      相关资源
      最近更新 更多