21xrx.com
2025-04-01 20:06:03 Tuesday
文章检索 我的文章 写文章
C++字符串相等的比较方法
2023-07-05 04:59:55 深夜i     17     0
C++ 字符串 比较方法 相等 字符串比较

在C++中,字符串是一种常见的数据类型,我们需要经常比较两个字符串是否相等。有多种方法可以比较字符串相等,本文将介绍三种常用的方法。

第一种方法是使用标准库函数strcmp()。strcmp() 函数比较两个字符串并返回一个整数。如果两个字符串相等,返回值为 0,否则返回一个非零值。代码如下:

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

第二种方法是使用标准库函数std::string的比较操作符"==",代码如下:

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

第三种方法是使用标准库函数std::equal(),代码如下:

#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
bool equal_str(const char* s1, const char* s2)
{
  return strlen(s1) == strlen(s2) && std::equal(s1, s1 + strlen(s1), s2);
}
int main()
{
  char str1[] = "Hello";
  char str2[] = "World";
  
  if(equal_str(str1, str2))
    cout << "两个字符串相等" << endl;
  else
    cout << "两个字符串不相等" << endl;
  return 0;
}

以上就是三种常用的比较字符串相等的方法。在实际编程中,选择哪种方法取决于程序的需求和情况。

  
  

评论区

请求出错了