在多个字符串中找到相同的字符串

时间:2018-09-10 08:17:09

标签: c++

您将如何尝试查找可能多次出现在std :: string str1 中的某个std :: string str2 ,并将职位存储在列表中还是矢量? 我要一个大概的主意,这样就够了,不用去尝试通过str2.length()存储单词的整个位置了。

1 个答案:

答案 0 :(得分:0)

std::string::find带有一个pos参数,该参数告诉它从哪里开始搜索。因此,您可以使用找到的最后一个位置(从0开始)创建一个简单的循环:

std::vector<size_t> positions;
std::string str1{"blabliblablubla"};
std::string str2{"bla"};
size_t pos = 0;
while((pos = str.find(str2, pos)) != std::string::npos)
{
    positions.push_back(pos);
    pos++;
}