这段代码有问题,我正在尝试验证一个字母是否在一个单词中,但由于某些原因,它不允许我输入 ==
。
#include <string>
#include <iostream>
using namespace std;
bool Verification(string a, string b)
{
bool VF = false;
for (int i = 0; i < a.size(); i++)
{
if (a[i] == b) //Here is the problem
{
VF = true;
}
}
return VF;
}
最佳答案
a
是一个字符串,b
是一个字符串。
a[i]
是一个 char
。您将 char
与 string
进行比较 - 显然,它不会起作用。
如果您想检查字母(即char
)是否存在于句子(即字符串
)中), 你可以这样实现这个功能:
bool Verification(string a, char b) // <-- notice: b is char
{
bool VF = false;
for (int i = 0; i < a.size(); i++)
{
if (a[i] == b)
{
VF = true;
}
}
return VF;
}
// Usage:
Verification("abc", 'a'); // <-- notice: quotes are double for string and single for char
其实有一个方法 string::find
,这可以帮助您在另一个 string
中找到 string
或 char
的出现
您可以将代码替换为:
#include <string>
#include <iostream>
using namespace std;
bool Verification(string a, char b)
{
return a.find(b) != string::npos;
}
关于c++ - 没有运算符 "=="匹配这些操作数字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33294776/