21xrx.com
2025-04-14 18:18:37 Monday
文章检索 我的文章 写文章
C++中字符串相等的比较
2023-06-26 18:25:55 深夜i     19     0
C++字符串 比较 相等

C++中字符串是一种常见的数据类型,常常需要进行字符串的比较操作。关于字符串的比较,有以下几种方式。

1. 直接用"=="进行比较

在C++中,字符串可以用双引号括起来表示,如"hello world"、"abc"等等。如果想要判断两个字符串是否相等,可以使用双等号"=="进行比较。

例如,下面的代码片段演示了用"=="进行字符串的比较操作:

#include <iostream>
#include <string>
using namespace std;
int main()
{
  string str1 = "hello";
  string str2 = "world";
  string str3 = "hello";
  if (str1 == str2)
  
    cout << "str1 is equal to str2" << endl;
  
  else
  
    cout << "str1 is not equal to str2" << endl;
  
  if (str1 == str3)
  
    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

可以看到,当两个字符串内容一致时,使用"=="进行比较操作会返回true,否则返回false。

2. 使用string类提供的成员函数进行比较

除了"=="运算符,C++中还提供了一些string类的成员函数,可以用来进行字符串的比较操作。

常用的成员函数有:

- compare(const string& str):比较当前字符串和str是否相等,相等则返回0,否则返回正数或负数。

- compare(const char* s):比较当前字符串和C风格字符串s是否相等,相等则返回0,否则返回正数或负数。

- compare(const string& str, size_t pos, size_t len):比较当前字符串和str从pos开始、长度为len的子串是否相等,相等则返回0,否则返回正数或负数。

- compare(const char* s, size_t n):比较当前字符串和C风格字符串s前n个字符是否相等,相等则返回0,否则返回正数或负数。

例如,下面的代码片段演示了使用string类的compare()函数进行字符串的比较操作:

#include <iostream>
#include <string>
using namespace std;
int main()
{
  string str1 = "hello";
  string str2 = "world";
  string str3 = "hello";
  int cmp1 = str1.compare(str2);
  int cmp2 = str1.compare(str3);
  if (cmp1 == 0)
  
    cout << "str1 is equal to str2" << endl;
  
  else
  
    cout << "str1 is not equal to str2" << endl;
  
  if (cmp2 == 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

同样可以看到,当两个字符串内容一致时,使用compare()函数进行比较操作会返回0,否则返回其他值。

综上所述,C++中提供了多种方式进行字符串的比较操作,根据实际应用场景选择合适的方式可以提高程序效率和可读性。

  
  

评论区

请求出错了