21xrx.com
2025-04-16 15:59:33 Wednesday
文章检索 我的文章 写文章
C++中如何判断两个字符串相等?
2023-07-10 04:20:34 深夜i     24     0
C++ 判断 两个字符串 相等

在C++编程中,判断两个字符串是否相等是经常使用的操作。如果两个字符串相等,则说明它们在内容和长度上完全相同。下面介绍几种判断两个字符串相等的方法。

1. 使用==运算符

C++中可以使用==运算符来比较两个字符串是否相等。例如:

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

运行结果为:

s1 and s3 are equal

2. 使用strcmp()函数

strcmp()函数是C++字符串库中的一种比较函数,可以根据字符串的ASCII码值来进行比较。如果两个字符串相等,则返回0。例如:

#include <iostream>
#include <cstring>
using namespace std;
int main() {
  char s1[] = "hello";
  char s2[] = "world";
  char s3[] = "hello";
  
  if (strcmp(s1, s2) == 0)
    cout << "s1 and s2 are equal" << endl;
  
  
  if (strcmp(s1, s3) == 0)
    cout << "s1 and s3 are equal" << endl;
  
  
  return 0;
}

运行结果为:

s1 and s3 are equal

3. 使用string::compare()函数

string::compare()函数是C++字符串库中的另一种比较函数,可以根据字符串的ASCII码值来进行比较。如果两个字符串相等,则返回0。例如:

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

运行结果为:

s1 and s3 are equal

综上所述,C++中有多种判断两个字符串相等的方法,比较常用的是使用==运算符和strcmp()函数。使用哪种方法可以根据具体情况而定。

  
  

评论区

请求出错了