Introduction
Counting the number of occurrences of a substring within a string is a common task in text processing and analysis. Whether you’re searching for specific keywords in a document, analyzing patterns in data, or processing user input, determining how many times a substring appears can provide valuable insights. Java 8 offers an efficient and concise way to accomplish this task using Streams. In this guide, we will explore how to create a Java program that counts the number of occurrences of a substring in a string using Java 8 Streams.
Problem Statement
The task is to create a Java program that:
- Accepts a string and a substring as input.
- Uses Java 8 Streams to count the number of times the substring appears in the string.
- Outputs the count of the substring’s occurrences.
Example 1:
- Input: String:
"hello world, hello universe", Substring:"hello" - Output:
Occurrences of "hello": 2
Example 2:
- Input: String:
"abababab", Substring:"ab" - Output:
Occurrences of "ab": 4
Solution Steps
- Input String and Substring: Start with a string and the substring you want to count. These can be either hardcoded or provided by the user.
- Check for Empty or Null Inputs: Ensure that neither the main string nor the substring is null or empty to avoid incorrect results.
- Count Occurrences: Use a loop or a more functional approach to count the occurrences of the substring within the main string.
- Display the Result: Print the total number of occurrences of the substring.
Java Program
Java 8 Program to Count the Number of Occurrences of a Substring in a String
/**
* Java 8 Program to Count the Number of Occurrences of a Substring in a String
* Author: https://www.rameshfadatare.com/
*/
public class SubstringOccurrencesCounter {
public static void main(String[] args) {
// Step 1: Take input string and substring
String input = "hello world, hello universe";
String substring = "hello";
// Step 2: Count the number of occurrences of the substring
long occurrences = countOccurrences(input, substring);
// Step 3: Display the result
System.out.println("Occurrences of \"" + substring + "\": " + occurrences);
}
// Method to count the number of occurrences of a substring in a string
public static long countOccurrences(String str, String subStr) {
if (str == null || subStr == null || subStr.isEmpty()) {
return 0;
}
return str.split("(?=" + subStr + ")").length - 1;
}
}
Explanation of the Program
-
Input Handling: The program uses the string
"hello world, hello universe"and the substring"hello"as example inputs. This can be modified to accept input from the user if required. -
Checking for Null or Empty Strings: The
countOccurrencesmethod checks if the main string or the substring is null or empty. If either is, the method returns0to avoid incorrect results. -
Counting Occurrences: The method uses the
split()function with a lookahead regular expression(?=subStr)to split the string at each occurrence of the substring. The length of the resulting array minus one gives the number of times the substring appears. -
Output: The program prints the number of occurrences of the substring within the input string.
Output Example
Example 1:
Input: "hello world, hello universe", Substring: "hello"
Output: Occurrences of "hello": 2
Example 2:
Input: "abababab", Substring: "ab"
Output: Occurrences of "ab": 4
Advanced Considerations
-
Overlapping Substrings: The approach used in this program counts overlapping occurrences. For example, in
"abab", the substring"ab"occurs twice. -
Performance Considerations: This method is efficient for typical string lengths. For very large strings, you might need to consider performance optimizations depending on the specific use case.
-
Handling Special Characters: The program handles special characters in the substring without issues. However, if the substring contains characters that have special meanings in regular expressions (e.g.,
".","*", etc.), you’ll need to escape them appropriately.
Conclusion
This Java 8 program efficiently counts the number of occurrences of a substring within a string. By leveraging the Stream API and regular expressions, the solution is both concise and powerful, making it suitable for various text processing tasks. Whether you’re searching for keywords, analyzing text patterns, or processing user input, this method provides an effective approach to counting substrings in Java.