1

Below i have a peice of code that compares two strings.

if (long.find(short) != string::npos) {
        cout << "FOUND";
}

This only tells me if it finds the short string in the long string. But how can i go about finding all the instances and tell the user where those instances of the string show?

I get the idea to maybe make this a loop but im having trouble implementing it.

soniccool
  • 5,790
  • 22
  • 60
  • 98

3 Answers3

1

You can do something like

#include <iostream>
#include <string>

int main()
{
    std::string test = "we are searching for searching here";
    std::string str = "searching";
    std::string::size_type start = test.find(str); // find the first instance
    while(start != std::string::npos) // repeat for the rest
    {
        std::cout << "Found on pos: " << start << std::endl;
        start = test.find(str, start + 1);
    }
}

Side note: don't use long and short as your string names, as they are C++ reserved keywords.

vsoftco
  • 55,410
  • 12
  • 139
  • 252
0

One of the overloads of find allows you to tell it where to start looking. So after finding one occurrence, call find() again with the previous location plus one.

Greg Hewgill
  • 951,095
  • 183
  • 1,149
  • 1,285
0

Here you go for a sample implementation:

#include<iostream>
#include<string>

int main() 
{
   std::string long_str ("abcabcabcabc");
   std::string short_str("abc"); 
   while( true)
   {
      std::size_t found = long_str.find(short_str);
      if (found == std::string::npos)
        break;
      long_str = long_str.substr(found+short_str.length());
      std::cout<<long_str<<"\n";
   }
}

Output:

abcabcabc

abcabc

abc

Steephen
  • 14,645
  • 7
  • 40
  • 47