21xrx.com
2025-03-28 20:48:18 Friday
文章检索 我的文章 写文章
C++中如何判断字符串相等
2023-07-07 13:18:45 深夜i     14     0
C++ 判断 字符串 相等

在C++语言中判断两个字符串是否相等是一种基本的操作,这在字符串处理中经常会用到。在C++中,判断字符串相等有多种方法,以下是其中的三种方法:

1.使用strcmp函数

strcmp函数是一个用于字符串比较的标准库函数,其语法如下:

int strcmp (const char* str1, const char* str2);

该函数用于比较str1和str2两个字符串。如果两个字符串完全相同,则返回0;如果str1小于str2,则返回负数;如果str1大于str2,则返回正数。

示例代码如下:

#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和str2相等" << endl;
   else
    cout << "str1和str2不相等" << endl;
  
  
  if (strcmp(str1, str3) == 0)
    cout << "str1和str3相等" << endl;
   else
    cout << "str1和str3不相等" << endl;
  
  
  return 0;
}

2.使用std::string类

C++中的std::string类提供了更方便的字符串操作方式,可以用==运算符来判断字符串相等。

示例代码如下:

#include <iostream>
#include <string>
using namespace std;
int main() {
  string str1 = "hello";
  string str2 = "world";
  string str3 = "hello";
  
  if (str1 == str2)
    cout << "str1和str2相等" << endl;
   else
    cout << "str1和str2不相等" << endl;
  
  
  if (str1 == str3)
    cout << "str1和str3相等" << endl;
   else
    cout << "str1和str3不相等" << endl;
  
  
  return 0;
}

3.自定义函数

除了使用标准库函数和std::string类提供的方法之外,我们也可以自定义一个函数来判断字符串相等。该函数的实现方式就是遍历两个字符串所有的字符,逐个进行比较,如果所有字符都相等,则返回true;否则返回false。

示例代码如下:

#include <iostream>
#include <cstring>
using namespace std;
bool is_equal(char* str1, char* str2) {
  int len1 = strlen(str1);
  int len2 = strlen(str2);
  if (len1 != len2)
    return false;
  
  for(int i = 0; i < len1; i++) {
    if (str1[i] != str2[i])
      return false;
    
  }
  return true;
}
int main() {
  char str1[] = "hello";
  char str2[] = "world";
  char str3[] = "hello";
  
  if (is_equal(str1, str2))
    cout << "str1和str2相等" << endl;
   else
    cout << "str1和str2不相等" << endl;
  
  
  if (is_equal(str1, str3))
    cout << "str1和str3相等" << endl;
   else
    cout << "str1和str3不相等" << endl;
  
  
  return 0;
}

以上三种方法都可以用来判断字符串相等,在实际开发中,开发者可以根据实际情况选择合适的方法来实现。

  
  

评论区