21xrx.com
2025-06-18 10:19:23 Wednesday
文章检索 我的文章 写文章
C++如何判断字符串是否相等?
2023-07-09 18:01:33 深夜i     52     0
C++ 字符串 判断 相等

在C++中,字符串是由字符数组组成的。因此,判断字符串是否相等,实际上就是比较两个字符数组是否相同。

C++中可以使用两种方法来判断两个字符串是否相等,分别是使用比较运算符“==”和使用字符串库函数strcmp()。

方法一:使用比较运算符“==”

下面是使用比较运算符“==”来判断字符串是否相等的示例代码:

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

输出结果为:

str1 and str3 are equal
str1 and str2 are not equal

方法二:使用字符串库函数strcmp()

strcmp()函数可以比较两个字符串,返回值为0表示两个字符串相等。下面是使用strcmp()函数来判断字符串是否相等的示例代码:

#include<iostream>
#include<cstring>
using namespace std;
int main() {
  char str1[] = "hello";
  char str2[] = "world";
  char str3[] = "hello";
  if (strcmp(str1, str3) == 0)
    cout << "str1 and str3 are equal" << endl;
  else
    cout << "str1 and str3 are not equal" << endl;
  if (strcmp(str1, str2) == 0)
    cout << "str1 and str2 are equal" << endl;
  else
    cout << "str1 and str2 are not equal" << endl;
  return 0;
}

输出结果为:

str1 and str3 are equal
str1 and str2 are not equal

以上就是C++中判断字符串是否相等的两种方法,你可以根据需要选择其中一种来使用。

  
  

评论区