Count occurrences of a substring: Difference between revisions

Content added Content deleted
(→‎{{header|Java}}: added shorter method)
Line 188: Line 188:


{{works with|Java|1.5+}}
{{works with|Java|1.5+}}
This method does a match and counts how many times it matches
This method removes the first occurrence of the substring, checks for changes, and continues if something changed. It counts each removal attempt (even if nothing is replaced), so the count starts at -1 to offset the last removal attempt where nothing changed.
<lang java>import java.util.regex.Pattern;
<lang java>import java.util.regex.Pattern;
import java.util.regex.Matcher;


public class CountSubstring {
public class CountSubstring {
public static int countSubstring(String subStr, String str){
public static int countSubstring(String subStr, String str){
int ans = 0;
int ans = -1;//start at -1 since we always count at least 1 replacement
Matcher m = Pattern.compile(Pattern.quote(subStr)).matcher(str);
String newStr = str;
while (m.find())
do{
str = newStr;
newStr = str.replaceFirst(Pattern.quote(subStr), "");//attempt a removal
ans++;//count it
ans++;//count it
}while(!str.equals(newStr));
return ans;
return ans;
}
}