C++ 相当于 Python 的 "if x in [string1, string2, …]"

标签 c++ string

我的小项目是制作一个聊天机器人;我没有谷歌开源,也没有研究如何构建。我正在尝试这样做以了解我对 C++ 的理解程度:说的是;

我正在尝试制作一个“盒子”,其中包含所有可以给出的“问题”,并查看“如果”“问题”“在”“盒子”中,它将执行所述代码。

在 Python 中,它或多或少是:

Box = ["Yes", "YES", "yes", "yEs", "YeS", "yES"]

print "Will you be working today?"
response = raw_input("> ")
if response in Box:
    print "Very well, then how can I assist you?"

那么我将如何在 C++ 中这样做。或者它在 C++ 中叫什么?数组?一个列表? vector ?在 C++ 中区分它们有点困惑。

最佳答案

为此,我会考虑将响应转换为所有小写,然后进行直接比较:

#include <string>
#include <cctype>
#include <functional>
#include <algorithm>

// convert string to lowercase
std::string lower_case(std::string s)
{
    std::transform(s.begin(), s.end(), s.begin()
        , std::ptr_fun<int, int>(std::tolower));
    return s;
}

int main()
{
    std::string response;

    // ask question and get response

    // now you don't need to look at every combination
    if(lower_case(response) == "yes")
    {
        // positive response code
    }

    // etc...
}

关于C++ 相当于 Python 的 "if x in [string1, string2, …]",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31622156/

相关文章:

regex - 如何匹配以 "I"开头但不是 "Integer"的单词?

c++ - BDS 2006 构建无外部依赖的可执行文件

c++ - 从重载的 operator[](模板?)返回不同的类型

c++ - 隐藏面移除 C++

c - 实现这种效果的代码更少?

c++ - string::c_str() 是否允许在堆上分配任何东西?

c - C语言判断字符串是否为空

swift - Swift 中的字符串比较是如何发生的

c++ - C题: no warning?

c++ - Qt项目中如何使用预编译头文件