Java - How to Count the Number of Occurrences of Substring in a String
In this section, we will write a Java program to Count the Number of Occurrences of Substring in a String.
Java program to Count the Number of Occurrences of Substring in a String
In the below program, we have countOccurrencesOf(String str, String sub) a generic method, here we simply pass input string and substring as arguments and method return number of occurrences of the substring.
/**
*
* Java program to count number of occurrence of substring in given string.
* @author knowledgefactory.net
*
*/
public class Main {
public static void main(String[] args) {
int count = countOccurrencesOf("javaknowledgefactoryjava", "java");
System.out.println("Count number of occurrences of substring 'java' " +
" in string 'javaknowledgefactoryjava' : " + count);
int count1 = countOccurrencesOf("javaknowledgefactoryjavajava", "java");
System.out.println("Count number of occurrences of substring 'java'" +
" in string 'javaknowledgefactoryjavajava' : " + count1);
}
public static boolean hasLength(String str) {
return (str != null && !str.isEmpty());
}
/**
* Count the occurrences of the substring {@code sub} in string {@code str}.
* @param str string to search in
* @param sub string to search for
*/
public static int countOccurrencesOf(String str, String sub) {
if (!hasLength(str) || !hasLength(sub)) {
return 0;
}
int count = 0;
int pos = 0;
int idx;
while ((idx = str.indexOf(sub, pos)) != -1) {
++count;
pos = idx + sub.length();
}
return count;
}
}
Console Output:
Count number of occurrences of substring 'java' in string 'javaknowledgefactoryjava' : 2
Count number of occurrences of substring 'java' in string 'javaknowledgefactoryjavajava' : 3
More related topics,