Java String Manipulation Java
Following code shows how to find frequency of a substring in a given string.
public class SubstringOccurrence { public static int getOccurrenceOfSubstring(final String input, String substring) { if (input == null || substring == null || substring.length()==0) { return 0; } Matcher matcher = Pattern.compile(Pattern.quote(substring)) .matcher(input); int count = 0; for (; matcher.find(); count++) ; return count; } public static void main(String[] args) { String input = "Is yours and yours and yours..."; int c = getOccurrenceOfSubstring(input, "yours"); System.out.println(c); c = getOccurrenceOfSubstring(input, "and"); System.out.println(c); c = getOccurrenceOfSubstring(input, "s"); System.out.println(c); c = getOccurrenceOfSubstring(input, " "); System.out.println(c); c = getOccurrenceOfSubstring(input,""); System.out.println(c); c = getOccurrenceOfSubstring(input,"."); System.out.println(c); } }
324503