Anonymous user
Count occurrences of a substring: Difference between revisions
→{{header|Java}}
(→{{header|Java}}: added shorter method) |
|||
Line 188:
{{works with|Java|1.5+}}
This method does a match and counts how many times it matches
<lang java>import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class CountSubstring {
public static int countSubstring(String subStr, String str){
int ans = 0;
Matcher m = Pattern.compile(Pattern.quote(subStr)).matcher(str);
while (m.find())
ans++;//count it
return ans;
}
|