Count occurrences of a substring: Difference between revisions
Content added Content deleted
Not a robot (talk | contribs) (Add Macro-11) |
|||
Line 1,655: | Line 1,655: | ||
=={{header|Java}}== |
=={{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+}} |
{{works with|Java|1.5+}} |
||
The "remove and count the difference" method: |
The "remove and count the difference" method: |