21xrx.com
2024-05-20 04:01:57 Monday
登录
文章检索 我的文章 写文章
如何在C++中比较字符串?
2023-07-13 20:41:15 深夜i     --     --
C++ 字符串 比较

在C++中比较字符串可以使用以下几种方法:

1. 使用strcmp()函数

_strcmp()函数是C++中的字符串比较函数,用于比较两个字符串是否相等,返回值为0表示相等,否则表示不相等。此函数接收两个参数,分别是要比较的字符串。

例如:


char str1[] = "Hello";

char str2[] = "World";

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

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

else

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

2. 使用==运算符

在C++中,可以使用==运算符来比较两个字符串是否相等,但是需要注意的是,==比较的是字符串的地址,而非字符串的内容。因此,如果要比较字符串的内容是否相等,必须使用strcmp()函数。

例如:


string str1 = "Hello";

string str2 = "World";

if (str1 == str2)

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

else

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

3. 使用compare()函数

compare()函数是string类的成员函数,用于比较两个字符串是否相等,返回值为0表示相等,否则表示不相等。此函数接收一个参数,即要比较的字符串。

例如:


string str1 = "Hello";

string str2 = "World";

if (str1.compare(str2) == 0)

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

else

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

总结:

使用上述方法可以在C++中比较字符串,其中strcmp()函数比较常用,如果使用string类型的变量,建议使用compare()函数。对于比较复杂的字符串,还可以使用正则表达式或自定义比较函数进行比较。

  
  

评论区

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