21xrx.com
2024-06-03 06:25:36 Monday
登录
文章检索 我的文章 写文章
C++如何判断两个字符串相等?
2023-07-05 11:54:00 深夜i     --     --
C++ 判断 字符串 相等

在C++中,如果你想要判断两个字符串是否相等,有几种方法可以使用。下面是一些常用的方法。

1. 使用strcmp函数

strcmp是一个C++内置函数,它可以比较两个字符串并返回相等与否的值。具体来说,strcmp函数接受两个参数:要比较的字符串s1和s2。如果s1和s2相等,则返回0。如果s1小于s2,则返回负数。如果s1大于s2,则返回正数。下面是一个使用strcmp函数的示例代码:


#include <iostream>

#include <string.h>

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;

}

2. 使用string类

C++的string类也提供了相等操作符==,可以用来判断两个字符串是否相等。下面是一个使用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类,因为它更易于使用和理解。如果你对C++语言更加熟练,也可以使用C++的内置函数来比较两个字符串。

  
  

评论区

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