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:

Comments

Popular posts from this blog

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

ReactJS - Bootstrap - Buttons

Spring Core | BeanFactoryPostProcessor | Example

Spring Boot 3 + Spring Security 6 + Thymeleaf - Registration and Login Example

File Upload, Download, And Delete - Azure Blob Storage + Spring Boot Example

Custom Exception Handling in Quarkus REST API

ReactJS, Spring Boot JWT Authentication Example

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

Top 5 Java ORM tools - 2024

Java - DES Encryption and Decryption example