Java Program to Count the Number of Occurrences of Substring in a String

In this blog post, we will write a Java program that counts the number of occurrences of a substring in a given string. This program utilizes string manipulation techniques and looping constructs to efficiently find and count the occurrences of the specified substring. Let's dive into the code and see how it works!

Java Program to Count the Number of Occurrences of Substring in a String

public class SubstringCount {
    public static void main(String[] args) {
        String inputString = "Java is a widely used programming language. Java is versatile and has a large community.";

        String substring = "Java";

        int count = countSubstringOccurrences(inputString, substring);

        System.out.println("Number of occurrences of \"" + substring + "\": " + count);
    }

    private static int countSubstringOccurrences(String inputString, String substring) {
        int count = 0;
        int index = 0;

        while ((index = inputString.indexOf(substring, index)) != -1) {
            count++;
            index += substring.length();
        }

        return count;
    }
}

Output:

Number of occurrences of "Java": 2

Explanation: 

1. The program starts by initializing the inputString variable with the original string and the substring variable with the substring we want to count occurrences of. 

2. The countSubstringOccurrences() method takes in the input string and the substring as parameters and returns the count of occurrences. 

3. Inside the countSubstringOccurrences() method, we initialize a count variable to keep track of the occurrences and an index variable to track the position in the string. 

4. The while loop executes as long as the indexOf() method finds occurrences of the substring in the input string. The indexOf() method returns the index of the first occurrence of the substring, or -1 if no more occurrences are found. 

5. If an occurrence is found, the count is incremented, and the index is updated to start the search from the next position by adding the length of the substring. 

6. Once all occurrences have been counted, the method returns the final count. 

7. Finally, the program prints the number of occurrences of the substring to the console. 

Feel free to modify the inputString and substring variables to test the program with different strings and substrings. 

Conclusion

In this blog post, we explored a Java program that counts the number of occurrences of a substring in a given string. By utilizing the indexOf() method and a loop, we efficiently search and count the occurrences. This program provides a useful tool for analyzing text and extracting specific patterns within strings. 

Feel free to incorporate this code into your Java projects or customize it to suit your specific requirements. Happy coding!

Related Java String Programs with Output

Comments