I am writing a function that searches for a substring in a given string and returns how many times the substring occurs in the string. For example, if the functions parameters were ("hellohello", "hel") the function would return 2. I apologize if the answer is obvious, I am relatively new to c++.
The if loop that i've created hasn't been working, and I'm not sure why. My function returns 0 when I call it in the main() function with its parameters set to ("hellohello", "hel").
int countMatches(string input, string substring)
{
if(input == "" || substring == "")
{
return -1;
}
else
{
int matches;
int substringLength = substring.length() - 1;
for(int i = 0; i < input.length(); i++)
{
if(input.substr(i, substringLength) == substring)
{
matches++;
return matches;
}
}
}
}
int main(){
//test 1
//expected output 2
cout << countMatches("hellohello", "hel") << endl;
}
Your problem specification is slightly ambiguous. Can the substrings overlap? For example, if you're looking for the number of times AA
occurs in AAAA
, do you consider the correct answer to be 2 or 3?
Either way, we can use std::string::find
to find the substrings. find
takes a parameter to specify where it should start looking for a match. So, if we want to allow overlapping sub-strings, we search from the beginning, then each time we find a sub-string we re-start the search from one position after the beginning of the match we found.
If we only want to allow non-overlapping sub-strings, we start the same (search from the beginning) but when we find a substring we restart the search from just past the end of the substring we just find.
So, here's a version that'll count overlapping substrings:
size_t count_substrings(std::string const &needle, std::string const &haystack) {
size_t count = 0;
for (size_t pos =0; (pos=haystack.find(needle, pos)) != std::string::npos; ++pos, ++count)
;
return count;
}
The modification necessary to count non-overlapping substrings is left as an exercise for the reader (but it honestly is pretty simple).
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments