I Spy Code - Java

Count how many times a substring appears in string

Question:

Write a java program that counts how many times a substring appears in a string.

Solution:

Here is a java example that determines how many times a substring occurs in a string: :

Source: (Example.java)

import org.apache.commons.lang.StringUtils;
 
public class Example {
 
    public static void main(String[] args) {
        String str = "a cat in the hat and a hat on a cat";
        System.out.println(str);
 
        System.out.println("hat: " + StringUtils.countMatches(str, "hat"));
        System.out.println("cat: " + StringUtils.countMatches(str, "cat"));
        System.out.println("a: " + StringUtils.countMatches(str, "a"));
    }
}
 

Output:

$ java Example
a cat in the hat and a hat on a cat
hat: 2
cat: 2
a: 8

References:

https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html#countMatches-java.lang.CharSequence-char-

Questions answered by this page:

Determining how many times a substring occurs in a string in java
frequency of a substring in a string