21xrx.com
2025-03-18 15:26:18 Tuesday
文章检索 我的文章 写文章
C++ 中如何比较两个字符串是否相等?
2023-07-12 09:24:54 深夜i     38     0
C++ 字符串 比较 相等

在C++中,比较两个字符串是否相等有多种方法。这里我们简单介绍两种常用的方法。

第一种方法是使用strcmp函数。strcmp函数可以比较两个字符串是否相等,其返回值为0代表两个字符串相等。下面是一个示例代码:

#include <iostream>
#include <cstring>
using namespace std;
int main()
{
  char str1[10] = "hello";
  char str2[10] = "world";
  if (strcmp(str1, str2) == 0)
    cout << "两个字符串相等" << endl;
   else
    cout << "两个字符串不相等" << endl;
  
  return 0;
}

第二种方法是使用==运算符。在C++中,可以直接使用==运算符判断两个字符串是否相等。下面是一个示例代码:

#include <iostream>
#include <cstring>
using namespace std;
int main()
{
  string str1 = "hello";
  string str2 = "world";
  if (str1 == str2)
    cout << "两个字符串相等" << endl;
   else
    cout << "两个字符串不相等" << endl;
  
  return 0;
}

需要注意的是,使用==运算符比较字符串时,要使用string类型而不是char类型。

以上是常用的两种比较字符串相等的方法。根据实际需求,可以选择使用其中一种或者多种方法。

  
  

评论区

请求出错了