Jump to content

Count occurrences of a substring: Difference between revisions

m
m (Clarify that the highest number of matches should be shown. Existing examples are fine.)
Line 38:
</pre>
=={{header|Java}}==
This method replacesremoves the first occurenceoccurrence of the substring, checks for changes, and continues if something changed. It counts each replacementremoval attempt (even if nothing is replaced), so the count starts at -1 to offset the last replacementremoval attempt where nothing changed.
<lang java>import java.util.regex.Pattern;
 
Line 47:
do{
str = newStr;
newStr = str.replaceFirst(Pattern.quote(subStr), "");//attempt a replacementremoval
ans++;//count it
}while(!str.equals(newStr));
Line 63:
2
2</pre>
 
=={{header|Perl}}==
<lang perl>sub countSubstring {
Anonymous user
Cookies help us deliver our services. By using our services, you agree to our use of cookies.