检查字符串是否在字符串中(字符串列表) [英] Check if string is in string (list of strings)

查看:155
本文介绍了检查字符串是否在字符串中(字符串列表)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是这里的新手,也是C ++的新手。我有一些python的经验,发现 if a in b真的很简单,我想知道C ++是否等效。

I'm new here and to C++. I've had some experience in python, and found "if a in b" really easy, and I'm wondering if there's an equivalent in C++.

背景

我一直在尝试创建一个字符串列表,并检查输入是否在该列表中。
之所以要这样做,是因为我只想在输入实际上在该函数中执行某项操作的情况下使用该函数。 (在这种情况下,更改int x和y坐标)

I've been trying to make a list of strings and check if an input is in that list. The reason I want to do this is because I want to only use a function if the input will actually do something in that function. (Change int x and y coordinates in this case)

问题

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

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

How do I check using an if whether the input myinput is included in string mylist?

推荐答案

您可以使用 std :: find

std::string myinput;
std::vector<std::string> mylist{"a", "b", "c"};

std::cin >> myinput;
if (std::find(std::begin(mylist), std::end(mylist), myinput) != std::end(mylist))
    // myinput is included in mylist.

这仅适用于三个字符串,但是如果您要使用更多字符串,则可以d最好使用 std :: set std :: unordered_set 更好。

This works fine with only three strings, but if you're going to have many more, you'd probably be better off with an std::set or std::unordered_set instead.

std::set<std::string> myset;
// put "a", "b", and "c" into the set here

std::cin >> myinput;
if (myset.find(myinput) != myset.end())
    // myinput is included in myset.

这篇关于检查字符串是否在字符串中(字符串列表)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆