Count occurrences of a substring: Difference between revisions
→{{header|Java}}
Not a robot (talk | contribs) (Add Macro-11) |
|||
Line 1,655:
=={{header|Java}}==
Using regular expression pattern matching
<syntaxhighlight lang="java">
int countSubstring(String string, String substring) {
substring = Pattern.quote(substring);
Pattern pattern = Pattern.compile(substring);
Matcher matcher = pattern.matcher(string);
int count = 0;
while (matcher.find())
count++;
return count;
}
</syntaxhighlight>
<br />
{{works with|Java|1.5+}}
The "remove and count the difference" method:
|