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:

Popular posts from this blog

Learn Java 8 streams with an example - print odd/even numbers from Array and List

Java Stream API - How to convert List of objects to another List of objects using Java streams?

Registration and Login with Spring Boot + Spring Security + Thymeleaf

Java, Spring Boot Mini Project - Library Management System - Download

ReactJS, Spring Boot JWT Authentication Example

Top 5 Java ORM tools - 2024

Java - Blowfish Encryption and decryption Example

Spring boot video streaming example-HTML5

Google Cloud Storage + Spring Boot - File Upload, Download, and Delete