21xrx.com
2024-09-20 00:50:08 Friday
登录
文章检索 我的文章 写文章
C++如何判断两个字符串是否相等?
2023-07-02 01:41:52 深夜i     --     --
C++ 判断 字符串 相等

在C++中,判断两个字符串是否相等可以使用字符串比较函数strcmp()。

strcmp()函数用于比较两个字符串是否相等,它的头文件是 。当两个字符串相等时,返回值为0;当第一个字符串大于第二个字符串时,返回值为正数;当第一个字符串小于第二个字符串时,返回值为负数。

下面是一个简单的示例:


#include <iostream>

#include <string.h>

int main() {

  char str1[] = "Hello";

  char str2[] = "World";

  char str3[] = "Hello";

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

    std::cout << "str1 and str2 are equal" << std::endl;

   else

    std::cout << "str1 and str2 are not equal" << std::endl;

  

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

    std::cout << "str1 and str3 are equal" << std::endl;

   else

    std::cout << "str1 and str3 are not equal" << std::endl;

  

  return 0;

}

在这个示例中,我们定义了三个字符串:str1、str2和str3,str1和str2不相等,而str1和str3相等。

使用strcmp()函数进行比较,用if语句判断其返回值是否为0,如果为0就说明两个字符串相等,否则说明不相等。

在实际开发中,另一个可选方案是使用string类型对象来比较两个字符串是否相等。可以使用string的成员函数compare()或者==运算符来完成比较。

使用string类型的示例如下:


#include <iostream>

#include <string>

int main() {

  std::string str1 = "Hello";

  std::string str2 = "World";

  std::string str3 = "Hello";

  if (str1 == str2)

    std::cout << "str1 and str2 are equal" << std::endl;

   else

    std::cout << "str1 and str2 are not equal" << std::endl;

  

  if (str1 == str3)

    std::cout << "str1 and str3 are equal" << std::endl;

   else

    std::cout << "str1 and str3 are not equal" << std::endl;

  

  return 0;

}

使用string类型对象比较的示例与使用strcmp()函数比较的示例很相似,只不过使用的是string类型的对象和成员函数。在这个示例中,我们定义了三个string类型的对象:str1、str2和str3,str1和str2不相等,而str1和str3相等。

使用==运算符来比较两个string对象是否相等,如果相等则返回true,否则返回false。

使用string类型的成员函数compare()也可以实现同样的效果。compare()函数返回值为0时,表示两个字符串相等。

在C++中,判断两个字符串是否相等有多种方法,可以根据具体的场景选择最适合的方法。使用字符串比较函数strcmp()或者string类型的成员函数compare()或==运算符都可以实现字符串的比较和判断字符串是否相等的功能。

  
  

评论区

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