Anonymous user
Count occurrences of a substring: Difference between revisions
→{{header|C++}}: Added C++ implementation
m (→{{header|Java}}: Typos) |
(→{{header|C++}}: Added C++ implementation) |
||
Line 10:
The matching should yield the highest number of non-overlapping matches. In general, this essentially means matching from left-to-right or right-to-left (see proof on talk page).
=={{header|C++}}==
<lang cpp>#include <iostream>
#include <string>
// returns count of non-overlapping occurrences of 'sub' in 'str'
int countSubstring(const std::string& str, const std::string& sub)
{
if (sub.length() == 0) return 0;
int count = 0;
for (size_t offset = 0;
(offset < str.length()) && ((offset = str.find(sub, offset)) != std::string::npos);
offset += sub.length())
{
++count;
}
return count;
}
int main()
{
std::cout << countSubstring("the three truths", "th") << '\n';
std::cout << countSubstring("ababababab", "abab") << '\n';
std::cout << countSubstring("abaabba*bbaba*bbab", "a*b") << '\n';
}</lang>
Output:
<pre>
3
2
2
</pre>
=={{header|ALGOL 68}}==
|