21xrx.com
2025-03-22 15:41:28 Saturday
文章检索 我的文章 写文章
C++如何判断字符数组是否相等?
2023-07-07 03:51:24 深夜i     30     0
C++ 字符数组 判断 相等

在C++中,判断两个字符数组是否相等非常重要。我们可以使用strcmp函数来实现这个功能。简单来说,strcmp函数是位于string.h头文件中的一个函数,它可以比较两个字符数组的大小,如果相等则返回0,否则返回一个非零的值来指示它们之间的关系。

下面是几个使用strcmp函数来判断字符数组相等的例子:

#include <iostream>
#include <string.h>
using namespace std;
int main()
{
  char str1[10] = "hello";
  char str2[10] = "world";
  char str3[10] = "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;
}

在上面的例子中,我们定义了三个字符数组str1、str2和str3,并通过strcmp函数比较它们的大小。第一个比较判断str1和str2是否相等,因为它们不相等,所以输出了“str1和str2不相等”的结果。第二个比较判断str1和str3是否相等,因为它们相等,所以输出了“str1和str3相等”的结果。

另外,如果你只是想简单地比较两个字符数组是否相等,还可以使用C++的运算符“==”来完成。这里也给出一个例子:

#include <iostream>
#include <string.h>
using namespace std;
int main()
{
  char str1[10] = "hello";
  char str2[10] = "hello";
  
  if (str1 == str2)
    cout << "str1 and str2 are equal" << endl;
  else
    cout << "str1 and str2 are not equal" << endl;
  return 0;
}

在这个例子中,我们定义了两个字符数组str1和str2,并使用“==”运算符比较它们的值。因为它们相等,所以输出了“str1和str2相等”的结果。

总之,无论你是使用strcmp函数还是使用“==”运算符,判断字符数组是否相等都是非常重要的,因为这可以帮助你准确地完成各种编程任务。

  
  

评论区

请求出错了