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 RJ Trujillo for Search a string for all occurrences of a substring in C++

$
0
0

I figured it out. I did not need a nested for loop because I was only comparing the secondary string to that of the string. It also removed the need to take the substring of the first string. SOOO... For those interested, it should have looked like this:

int countMatches(string str, string comp){    int small = comp.length();    int large = str.length();    int count = 0;    // If string is empty    if (small == 0 || large == 0) {        return -1;    }    // Increment i over string length    for (int i = 0; i < large; i++) {        // Output substring stored in string        if (comp == str.substr(i, small)) {            count++;        }    }    cout << count << endl;    return count;}

Viewing all articles
Browse latest Browse all 4

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>