-1

How would you go about trying to find a certain std::string str2 that could be in std::string str1 multiple times and storing the positions in a list or vector? I'm asking for a rough idea and it's good enough to leave out trying to store the whole position of the word by str2.length().

Tyron
  • 25
  • 1
  • 6
  • 1
    do you know how to find the first occurence of `str2` in `str1` ? Please show some code, explain what you tried and how it fails. SO is not a codewriting service – 463035818_is_not_an_ai Sep 10 '18 at 08:19
  • I did try std::find with std::size_t but that seems to work only for one occurance. It may be that don't know of a working method so far – Tyron Sep 10 '18 at 08:27
  • ...next question would be: what did you notice when you called `std::find` ? What do you pass as first parameter (or second parameter if you use `std::string::find`)? ...anyhow, you already got your answer ;) – 463035818_is_not_an_ai Sep 10 '18 at 08:31

1 Answers1

0

std::string::find takes a pos parameter, that tells it where to start searching. So you can create a simple loop using the last pos it found (starting at 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++;
}
Max Vollmer
  • 8,412
  • 9
  • 28
  • 43