Quantcast
Channel: Search a string for all occurrences of a substring in C++ - Stack Overflow
Viewing all articles
Browse latest Browse all 4

Answer by Davide Spataro for Search a string for all occurrences of a substring in C++

$
0
0

The problem with your function is that you are checking that:

  • Hello is substring of Hello
  • ello is substring of ello
  • llo is substring of llo
  • ...

of course this matches 5 times in this case.


What you really need is:

  • For each position i of str
  • check if the substring of str starting at i and of length = comp.size() is exactly comp.

The following code should do exactly that:

size_t countMatches(const string& str, const string& comp){    size_t count = 0;    for (int j = 0; j < str.size()-comp.size()+1; j++)         if (comp == str.substr(j, comp.size()))              count++;    return count;}

Viewing all articles
Browse latest Browse all 4

Latest Images

Trending Articles



Latest Images