简体   繁体   English

如何在C ++中将字符串与const字符串进行比较

[英]How to compare a string to a const string in C++

Let's say I have the following poc code: 假设我有以下POC代码:

const string& a = "hello";
string b = "l";

if(a.at(2) == b)
{
 // do stuff
} 

I understand that there is no operator "==" that matches these operands. 我了解没有匹配这些操作数的运算符“ ==”。 And, the way to fix it is by converting the value of the variable a into 'hello' (instead of double quotes) as char. 并且,解决此问题的方法是将变量a的值转换为char形式的“ hello”(而不是双引号)。

However, what if I have no choice but performing the comparison as shown in the code. 但是,如果我别无选择,只能执行代码中所示的比较该怎么办。 Is it possible? 可能吗? Could you please provide any guidance or suggestions you might have on this issue. 您能否提供有关此问题的任何指导或建议。

Your responses are appreciated. 感谢您的答复。

You're comparing a char (to be specific a const char ) and a std::string , of which there exists no overloaded comparison operator for ( operator== ). 您正在比较一个char (具体来说是const char )和一个std::string ,其中没有用于( operator== )的重载比较运算符。

You have some options: 您有一些选择:

(1) compare b 's first character to the character you're wanting to compare to (1)将b的第一个字符与您要比较的字符进行比较

string b = "l";
string a = "hello";
if(a[2] == b[0]) { /* .. */ }

(2) convert a[2] to a std::string (2)将a[2]转换为std::string

string b = "l";
string a = "hello";
if(string{a[2]} == b) { /* .. */ }

(3) let b be a char (3)令b为一个char

char b = 'l';
string a = "hello";
if(a[2] == b) { /* .. */ }

Also, you should not construct a string object like this 另外,您不应该像这样构造一个字符串对象

const string& a = "hello";

unless you actually want to create a reference to another string object, eg 除非您实际上想创建对另一个字符串对象的引用,例如

string x = "hello";
const string& a = x;
const string& a = "hello";
string b = "l";

if (a[2] == b[0])
{
    // do stuff
}

a.at(2) is not string. a.at(2)不是字符串。 when do b to b[0] problem solving. b到b [0]何时解决问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM