1

I want to use function search or other similar function to find multiple occurrence of given pattern.

This is my code:

#include <cstring>  
#include <iostream> 
#include <iomanip>  
#include <set>
#include <list>
#include <vector>
#include <map>   
#include <algorithm>
#include <functional>
using namespace std;

int main () {
  std::vector<int> haystack;

  string a = "abcabcabc";
  string b = "abc";
  string::iterator it;
  it = search(a.begin(),a.end(),b.begin(),b.end());

  if(it!=a.end()){
      cout << it-a.begin()<<endl;
  }

  return 0;
}

This code return 0 as the first occurrence of pattern "abc" , would like to return 0, 3, 6. That would be all of the indexes in the original string where pattern begins.

Thank you for any help.

Ethan
  • 249
  • 1
  • 2
  • 10
Pastx
  • 687
  • 3
  • 8
  • 23
  • 2
    possible duplicate of [Find all a substring's occurrences and locations](http://stackoverflow.com/questions/4034750/find-all-a-substrings-occurrences-and-locations) – Cory Kramer Apr 14 '14 at 13:52
  • You need a loop, which should finish when `it == a.end()`. What did you try? And is there any particular reason you aren't using `a.find`? – Useless Apr 14 '14 at 13:53

3 Answers3

3
for(size_t pos=a.find(b,0); pos!=std::string::npos; pos=a.find(b,pos+1)) {
    std::cout << pos << std::endl;
}    

This uses std::basic_string::find (ref) directly to find the starting position of the substring.

Danvil
  • 22,240
  • 19
  • 65
  • 88
1

The search function searches the first string a for any occurence of the elements of the second string b. As Your second string contains the elements a, b and c the code would return an iterator to the first position, then to the second, the third one,...

What You what to use is the find function. It returns an iterator to the element that equals the one that You were searching for. In Your case You're search the string a for the element abc. So You would have to call

string::iterator it = std::find(a.begin(), a.end(), "abc");
while (it != a.end()) {
    // Do whatever you want to do...
    ++it;
    it = std::find(it, a.end(), "abc");
}
sleepy1771
  • 313
  • 1
  • 8
0
//find first result index
auto find_index = str.find("st");
while(string::npos != find_index) {
  cout << "found at: " << find_index << endl;
  //find next
  find_index = str.find("st",find_index+1);
}
LE SANG
  • 10,955
  • 7
  • 59
  • 78