21xrx.com
2025-04-27 12:58:07 Sunday
文章检索 我的文章 写文章
如何在C++中比较两个字符串是否相等?
2023-06-23 18:27:50 深夜i     25     0
C++ 字符串 比较 相等 方法

在C++中,比较两个字符串是否相等是一个常见的问题。本文将介绍两种实现方式。

方法一:使用compare()函数

C++中的string类提供了一个compare()函数,用于比较两个字符串是否相等。

示例代码如下:

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

输出结果为"str1 and str2 are not equal",因为str1和str2不相等。

方法二:使用==运算符

C++中的string类还提供了==运算符,用于比较两个字符串是否相等。

示例代码如下:

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

输出结果为"str1 and str2 are not equal",因为str1和str2不相等。

总结:

比较两个字符串是否相等,可以使用string类提供的compare()函数或==运算符。其中,compare()函数返回0表示相等,返回非0则表示不相等;而==运算符直接返回true或false。根据实际需求,选择合适的方法进行比较即可。

  
  

评论区

请求出错了