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

Introduction

Counting the number of occurrences of a substring within a string is a common task in text processing. This can be useful for various purposes such as text analysis, data validation, and more. In this blog post, we'll explore different methods to count the number of occurrences of a substring in a given string using Java.

Table of Contents

  1. Using split() Method
  2. Using indexOf() Method
  3. Using Regular Expressions
  4. Complete Example Program
  5. Conclusion

1. Using split()() Method

One of the simplest ways to count the occurrences of a substring is by using the split() method. This method splits the string around matches of the given regular expression and returns an array of substrings.

Example:

public class SubstringCountUsingSplit {
    public static void main(String[] args) {
        String input = "Java is great. Java is fun. Java is powerful.";
        String substring = "Java";

        // Use split() to divide the input based on the substring
        String[] parts = input.split(substring, -1);

        // The count of occurrences of the substring is the number of parts minus one
        int count = parts.length - 1;

        System.out.println("Number of occurrences using split(): " + count);
    }
}

Explanation:

  • The split() method splits the string at each occurrence of the substring.
  • The length of the resulting array minus one gives the number of occurrences of the substring.

Output:

Number of occurrences using split(): 3

2. Using indexOf()() Method

Another approach is to use the indexOf() method in a loop to find each occurrence of the substring and increment a counter.

Example:

public class SubstringCountUsingIndexOf {
    public static void main(String[] args) {
        String input = "Java is great. Java is fun. Java is powerful.";
        String substring = "Java";

        int count = 0;
        int index = 0;

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

        System.out.println("Number of occurrences using indexOf(): " + count);
    }
}

Explanation:

  • The indexOf() method returns the index of the first occurrence of the specified substring.
  • By incrementing the index by the length of the substring each time, the loop continues to find subsequent occurrences.

Output:

Number of occurrences using indexOf(): 3

3. Using Regular Expressions

Using regular expressions with the Pattern and Matcher classes provides a powerful way to count occurrences of a substring.

Example:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class SubstringCountUsingRegex {
    public static void main(String[] args) {
        String input = "Java is great. Java is fun. Java is powerful.";
        String substring = "Java";

        Pattern pattern = Pattern.compile(substring);
        Matcher matcher = pattern.matcher(input);

        int count = 0;
        while (matcher.find()) {
            count++;
        }

        System.out.println("Number of occurrences using regex: " + count);
    }
}

Explanation:

  • Pattern.compile(substring) compiles the substring into a pattern.
  • The Matcher class is used to find occurrences of the pattern in the input string.

Output:

Number of occurrences using regex: 3

4. Complete Example Program

Here is a complete program that demonstrates all the methods discussed above to count the number of occurrences of a substring in a string.

Example Code:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class SubstringCountExample {
    public static void main(String[] args) {
        String input = "Java is great. Java is fun. Java is powerful.";
        String substring = "Java";

        // Using split() method
        String[] parts = input.split(substring);
        int countUsingSplit = parts.length - 1;
        System.out.println("Number of occurrences using split(): " + countUsingSplit);

        // Using indexOf() method
        int countUsingIndexOf = 0;
        int index = 0;
        while ((index = input.indexOf(substring, index)) != -1) {
            countUsingIndexOf++;
            index += substring.length();
        }
        System.out.println("Number of occurrences using indexOf(): " + countUsingIndexOf);

        // Using Regular Expressions
        Pattern pattern = Pattern.compile(substring);
        Matcher matcher = pattern.matcher(input);
        int countUsingRegex = 0;
        while (matcher.find()) {
            countUsingRegex++;
        }
        System.out.println("Number of occurrences using regex: " + countUsingRegex);
    }
}

Output:

Number of occurrences using split(): 3
Number of occurrences using indexOf(): 3
Number of occurrences using regex: 3

5. Conclusion

Counting the number of occurrences of a substring within a string can be achieved in multiple ways in Java. The split() method, indexOf() method, and regular expressions each provide a unique approach, offering flexibility depending on your specific requirements. By understanding and using these different methods, you can choose the most appropriate one for your text processing needs.

Happy coding!

Related Java String Programs with Output

Comments

  1. public class SubstringCountUsingSplit {
    public static void main(String[] args) {
    // Take a String
    String str = "Java is great. Java is the future Java";
    // Take any subString from string
    String subString = "Java";
    // Use split
    String[] input = str.split(subString);

    // Print the array to see what split produces
    for (String part : input) {
    System.out.println("Part: \"" + part + "\"");
    }

    // Calculate the count of the substring
    int countSubString = input.length - 1;
    System.out.println("countSubString::::::" + countSubString);
    }
    }
    output:
    Part: ""
    Part: " is great. "
    Part: " is the future "
    countSubString::::::2
    Expected Output:
    Part: ""
    Part: " is great. "
    Part: " is the future "
    countSubString::::::3,Please correct it Sir

    ReplyDelete

Post a Comment

Leave Comment