我很抱歉这个简单的问题,但我不明白为什么这个简单的程序不起作用.
什么是a[0]应该比其他"a"?
#include <iostream>
using namespace std;
int main(){
string a = "abcd";
string b = "a";
if (a[0]==b){//<------problem here
cout << a << endl;
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
它返回错误
不匹配'operator =='(操作数类型是'char'和'std :: __ cxx11 :: string {aka std :: __ cxx11 :: basic_string <char>}')
或者只是使用string c=a[0];返回错误:
请求从'char'转换为非标量类型'std :: __ cxx11 :: string {aka std :: __ cxx11 :: basic_string <char>}'
PS:在尝试了一些事情之后,如果我比较a[0]==b[0]或分配,我可以让它工作,c[0]=a[0]因为那些现在绝对是相同的类型,但我仍然想知道什么是标准和/或最快的方式来进行比较在C++中使用另一个字符串的子字符串是.
您应该使用std :: string :: find来查找子字符串.在字符串上使用下标运算符返回单个字符(标量),而不是字符串(向量,非标量); 因此,它们不是同一类型,也没有明确的比较.
您也可以使用std :: string :: substr选择一个可以直接与另一个字符串进行比较的子字符串.
例
#include <iostream>
#include <string>
int
main() {
std::string a = "abcd";
std::string b = "a";
if (a.find(b) != std::string::npos) {
std::cout << a << "\n";
}
if (a.substr(0, 1) == b) {
std::cout << a << "\n";
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
参考
http://en.cppreference.com/w/cpp/string/basic_string/find
http://en.cppreference.com/w/cpp/string/basic_string/substr
http://en.cppreference.com/w/ CPP /串/ basic_string的