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

Search a string for all occurrences of a substring in C++

$
0
0

Write a function countMatches that searches the substring in the given string and returns how many times the substring appears in the string.

I've been stuck on this awhile now (6+ hours) and would really appreciate any help I can get. I would really like to understand this better.

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 < small; i++) {        // Output substring stored in string        for (int j = 0; j < large; j++) {            if (comp.substr(i, small) == str.substr(j, large)) {                count++;            }        }    }    cout << count << endl;    return count;}

When I call this function from main, with countMatches("Hello", "Hello"); I get the output of 5. Which is completely wrong as it should return 1. I just want to know what I'm doing wrong here so I don't repeat the mistake and actually understand what I am doing.


Viewing all articles
Browse latest Browse all 4

Trending Articles



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