21xrx.com
2024-09-19 10:02:03 Thursday
登录
文章检索 我的文章 写文章
如何判断C++字符串是否相等?
2023-07-05 10:53:13 深夜i     --     --
C++ 字符串 判断 相等

在C++中,字符串是一种重要的数据类型,我们通常需要判断两个字符串是否相等。判断字符串相等有多种方法,本文将介绍几种常见的方法。

1. 使用strcmp()函数

strcmp()函数可以比较两个字符串是否相等。该函数的语法如下:


#include <cstring>

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

其中,str1和str2是要比较的字符串。如果两个字符串相等,则返回值为0;如果第一个字符串小于第二个字符串,则返回值为负数;如果第一个字符串大于第二个字符串,则返回值为正数。下面是一个使用strcmp()函数的示例:


#include <cstring>

#include <iostream>

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;

}

输出:


str1 != str2

str1 == str3

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 == str2" << endl;

  else

    cout << "str1 != str2" << endl;

  if (str1 == str3)

    cout << "str1 == str3" << endl;

  else

    cout << "str1 != str3" << endl;

  return 0;

}

输出:


str1 != str2

str1 == str3

3. 使用比较运算符

可以使用C++中的比较运算符(>、<、>=、<=)比较两个字符串的大小关系,如果两个字符串相等,则返回false。下面是一个使用比较运算符的示例:


#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 if (str1 < str2)

    cout << "str1 < str2" << endl;

  else

    cout << "str1 == str2" << endl;

  if (str1 >= str3)

    cout << "str1 >= str3" << endl;

  if (str1 <= str3)

    cout << "str1 <= str3" << endl;

  return 0;

}

输出:


str1 < str2

str1 == str3

str1 <= str3

以上就是几种判断C++字符串相等的方法,根据具体情况选择合适的方法即可。建议使用==运算符或strcmp()函数,因为它们比较简单易懂。使用比较运算符时需要注意,不要将两个字符串相等与两个字符串相等的大小比较混淆。

  
  

评论区

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