c++ - 没有运算符 "=="匹配这些操作数字符串

标签 c++

这段代码有问题,我正在尝试验证一个字母是否在一个单词中,但由于某些原因,它不允许我输入 ==

#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。您将 charstring 进行比较 - 显然,它不会起作用。

如果您想检查字母(即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 中找到 stringchar 的出现 您可以将代码替换为:

#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/

相关文章:

c++ - 在 C++ 中将两个返回 unique_ptr 和 shared_ptr 的工厂方法合并为一个?

c++ - 通过指针偏移访问结构变量值

c++ - g++ : linker issue on Mac OS X - Undefined symbols for architecture x86_64

c++ - 线程体系结构问题 C++ 消息传递

c++ - 我如何处理队列前端和弹出功能

c++ - strftime 将不需要的字符添加到我要显示的内容中

c++ - 间接运算符是否会更改内存表示?

c++ - 类名没有命名类型

c++ - 声明与类型不兼容

c++ - 如何使用线程每 0.3 秒发送一次消息?