21xrx.com
2024-09-20 00:41:36 Friday
登录
文章检索 我的文章 写文章
C++如何判断字符串相等
2023-07-01 15:39:32 深夜i     --     --
C++ 字符串 判断 相等 比较

在C++语言中,判断字符串相等一直是一个比较常见的问题。关于如何判断字符串相等,可以使用以下几种方式:

1. 使用strcmp函数判断字符串相等

C++中提供了一个常用的字符串比较函数strcmp,可以使用该函数判断两个字符串是否相等。strcmp函数会比较两个字符串的ASCII码值,如果两个字符串相等返回0,否则返回一个非零值,根据这个返回值就可以判断两个字符串是否相等。

示例代码如下:


#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 is equal to str2" << endl;

   else

    cout << "str1 is not equal to str2" << endl;

  

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

    cout << "str1 is equal to str3" << endl;

  else

    cout << "str1 is not equal to str3" << endl;

  

  return 0;

}

2. 使用字符串的==运算符判断字符串相等

在C++中,字符串也是可以使用==运算符进行比较的。当两个字符串完全相等时,==运算符会返回true,否则返回false。

示例代码如下:


#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;

}

以上就是C++中判断字符串相等的两种方法。大家可以根据实际情况选择使用哪种方法,从而更好的完成自己的程序。

  
  

评论区

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