如何检查字符串是否在字符串列表中?

新手上路,请多包涵

在 Python 中,做 if a in b 真的很容易,我想知道 C++ 中是否有等价物。

具体来说,我想制作一个字符串列表并检查输入是否在该列表中。

 std::string myinput;
std::string mylist[] = {"a", "b", "c"};
std::cin >> myinput;
// if myinput is included in mylist
// do other stuff here

如何使用 if 检查输入 myinput 是否包含在字符串 mylist 中?

原文由 Sumyjkl 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.1k
1 个回答

您也可以使用 std::count

 #include <iostream>
#include <algorithm>  // std::count
#include <vector>

//using namespace std;

int main() {
    std::vector<std::string> ans = {"a", "b", "c", "a"};
    std::cout << count(ans.begin(), ans.end(), "a") << std::endl;
    return 0;
}

如果数字 > 0 ,则表示字符串在字符串中。

原文由 Hu Xixi 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题