In this post, we will discuss and write Java program to count the number of occurrences of a substring in a String.
Let's write a most efficient program with simple logic.
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.
package com.javaguides.strings.examples; /** * * Java program to count number of occurrence of substring in given string. * @author javaguides.net * */ public class CountOccuranceOfSubString { public static void main(String[] args) { int count = countOccurrencesOf("javadevelopersguides", "java"); System.out.println("Count number of occurrences of substring 'java' " + " in string 'javadevelopersguides' : " + count); int count1 = countOccurrencesOf("javajavaguides", "java"); System.out.println("Count number of occurrences of substring 'java'" + " in string 'javajavaguides' : " + 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; } }
Output:
Count number of occurrences of substring 'java' in string 'javadevelopersguides' : 1
Count number of occurrences of substring 'java' in string 'javajavaguides' : 2
You can use this method as a common utility static method in your project work.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Related String Programs
Note that these programs are asked in interviews.- Java program to Count Number of Duplicate Words in String
- Java Program to Count Number of Words in Given String
- Java Program to Count the Number of Occurrences of Substring in a String
- Java Program to Count the Occurrences of Each Character in String
- Java Program to Merge two String Arrays
- Java Program to Remove Duplicate Words from String
- Java Program to Reverse a String(5 ways)
- Java Program to Reverse Each Word of a String
- Java Program to Swap Two Strings
- How to Check if the String Contains only Digits
- How to Check if the String Contains only Letters
- How to Check If the String Contains Only Letters or Digits
Free Spring Boot Tutorial | Full In-depth Course | Learn Spring Boot in 10 Hours
Watch this course on YouTube at Spring Boot Tutorial | Fee 10 Hours Full Course