21xrx.com
2024-09-20 00:17:43 Friday
登录
文章检索 我的文章 写文章
如何用C++判断字符数组是否相等?
2023-06-30 20:04:42 深夜i     --     --
C++ 判断 字符数组 相等

在C++中,要判断两个字符数组是否相等,可以使用 strcmp() 函数。strcmp() 函数比较两个字符串(字符数组)的内容,如果相等则返回0,否则返回一个非0值,值的大小表示第一个不相等字符的 ASCII 码差值。

以下是使用 strcmp() 函数进行字符数组比较的示例代码:


#include <iostream>

#include <cstring>

using namespace std;

int main()

{

  char str1[] = "hello";

  char str2[] = "world";

  char str3[] = "hello";

  if (strcmp(str1, str2) == 0)

    cout << "str1 and str2 are equal" << endl;

  else

    cout << "str1 and str2 are not equal" << endl;

  if (strcmp(str1, str3) == 0)

    cout << "str1 and str3 are equal" << endl;

  else

    cout << "str1 and str3 are not equal" << endl;

  return 0;

}

在上面的代码中,使用了 strcmp() 函数来比较三个字符数组 str1、str2 和 str3。第一个 if 语句返回 false,因为 str1 和 str2 不相等。第二个 if 语句返回 true,因为 str1 和 str3 相等。

注意,在 C++ 中,字符数组的比较不能直接使用 == 运算符,因为它会比较数组的地址而不是数组的内容。因此,必须使用 strcmp() 函数来比较字符数组的内容。

除了 strcmp() 函数外,C++ 还提供了其他比较函数和算法,如 stricmp()、memcmp()、std::equal() 等,可以根据需要选择合适的函数。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复