21xrx.com
2025-03-31 10:00:46 Monday
文章检索 我的文章 写文章
C++中比较两个字符串是否相等的方法
2023-06-28 04:00:07 深夜i     24     0
C++ 字符串 比较 相等 方法

在C++中,比较两个字符串是否相等的方法有很多种。字符串是由一系列字符组成的,因此比较字符串是否相等就是比较它们的字符是否一致。下面是两种在C++中比较字符串是否相等的方法:

方法一:使用字符串类的compare()函数

字符串类提供了一种方便的方式来比较两个字符串是否相等。C++中的字符串类有std::string,它包含了许多用于处理字符串的函数。其中,比较两个字符串是否相等的函数是compare()。compare()函数返回一个整数值,如果两个字符串相等,那么返回值为0;如果字符串不相等,返回值为非0。

下面是使用字符串类的compare()函数来比较两个字符串是否相等的示例代码:

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

输出结果为:

str1 is not equal to str2                                                
str1 is equal to str3

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

C字符串是一种比较基础的字符串类型,它是以零结尾的一串字符。在C++中,可以使用C字符串的strcmp()函数来比较两个字符串是否相等。strcmp()函数返回一个整数值,如果两个字符串相等,返回值为0;如果字符串不相等,返回值为非0。

下面是使用C字符串的strcmp()函数来比较两个字符串是否相等的示例代码:

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

输出结果为:

str1 is not equal to str2
str1 is equal to str3

总结

比较两个字符串是否相等是一个常见的操作。在C++中,可以使用字符串类的compare()函数或C字符串的strcmp()函数来实现这个功能。两者的返回值都是相同的,如果相等返回值为0,不相等则返回非0。如果只需要进行简单的字符串比较,推荐使用字符串类的compare()函数。如果需要对字符串进行复杂的处理,或者需要进行更底层的操作,那么使用C字符串的strcmp()函数会更加方便。

  
  

评论区