Count occurrences of a substring: Difference between revisions
Content deleted Content added
added php |
→{{header|Java}}: added shorter method |
||
Line 168: | Line 168: | ||
=={{header|Java}}== |
=={{header|Java}}== |
||
{{works with|Java|1.5+}} |
|||
The "remove and count the difference" method: |
|||
<lang java>public class CountSubstring { |
|||
public static int countSubstring(String subStr, String str){ |
|||
return (str.length() - str.replace(subStr, "").length()) / subStr.length(); |
|||
} |
|||
public static void main(String[] args){ |
|||
System.out.println(countSubstring("th", "the three truths")); |
|||
System.out.println(countSubstring("abab", "ababababab")); |
|||
System.out.println(countSubstring("a*b", "abaabba*bbaba*bbab")); |
|||
} |
|||
}</lang> |
|||
Output: |
|||
<pre>3 |
|||
2 |
|||
2</pre> |
|||
{{works with|Java|1.5+}} |
|||
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. |
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; |