21xrx.com
2024-06-03 04:42:52 Monday
登录
文章检索 我的文章 写文章
如何在C++中比较字符串是否相等
2023-07-01 06:06:05 深夜i     --     --
C++ 字符串 比较 相等

在C++中,比较字符串是否相等是非常常见的操作。不像其他编程语言中直接使用“==”来判断,C++ 中的字符串比较有所不同。下面讲解几种 C++ 中比较字符串是否相等的方法。

1. strcmp() 函数

strcmp() 函数是C语言中最常用的比较字符串的函数。它可以用来比较两个字符串是否相等。在 C++ 中,可以使用 strcmp() 函数来实现字符串比较。例如,下面的代码演示了如何使用 strcmp() 函数比较两个字符串是否相等:


#include <iostream>

#include <cstring>

using namespace std;

int main() {

  char str1[] = "Hello, world!";

  char str2[] = "Hello, world!";

  

  if (strcmp(str1, str2) == 0)

    cout << "The two strings are equal." << endl;

   else

    cout << "The two strings are not equal." << endl;

  

  

  return 0;

}

在这个示例中,strcmp() 函数接受两个参数,它会比较这两个字符串是否相等。如果两个字符串相等,函数返回 0,否则返回一个非 0 的值。

2. string 类型比较

C++ 中提供了 string 类型,这个类型包含了比较字符串的方法。在 C++ 中,可以直接使用“==”号来比较两个字符串是否相等。例如,下面的代码演示了如何使用 string 类型比较两个字符串是否相等:


#include <iostream>

#include <string>

using namespace std;

int main() {

  string str1 = "Hello, world!";

  string str2 = "Hello, world!";

  

  if (str1 == str2)

    cout << "The two strings are equal." << endl;

   else

    cout << "The two strings are not equal." << endl;

  

  

  return 0;

}

在这个示例中,string 类型包含“==”运算符来比较两个字符串是否相等。如果两个字符串相等,运算符返回 true,否则返回 false。

3. C-style 字符串比较

除了使用 strcmp() 函数和 string 类型比较之外,C++ 还提供了一种比较 C-style 字符串的方法。使用 C-style 字符串比较的方法依赖于 C-style 字符串比较的规则。例如,下面的代码演示了如何使用 C-style 字符串比较方法比较两个字符串是否相等:


#include <iostream>

#include <cstring>

using namespace std;

int main() {

  char str1[] = "Hello, world!";

  char str2[] = "Hello, world!";

  

  if (strcmp(str1, str2) == 0)

    cout << "The two strings are equal." << endl;

   else

    cout << "The two strings are not equal." << endl;

  

  

  return 0;

}

在这个示例中,使用 strcmp() 函数来比较两个 C-style 字符串是否相等。如果结果为 0,那么两个字符串相等。如果结果不为 0,那么两个字符串不相等。

总结

在 C++ 中比较字符串是否相等可以使用 strcmp() 函数、string 类型比较和 C-style 字符串比较。无论使用哪种方法,都需要使用正确的语法来进行比较。熟练掌握比较字符串方法,将对编程有很大的帮助。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复