1. Introduction
Counting the occurrences of a substring in a given string is a common problem in Java programming. This problem has a wide range of applications, such as searching within documents, data analysis, and natural language processing. In this guide, we will create a Java program to count the occurrences of a specified substring within a given string using the indexOf method.
2. Program Steps
1. Define the main string and the substring whose occurrences we want to count.
2. Initialize a counter to keep track of the number of occurrences.
3. Use a loop and the indexOf method to find the positions of the substring in the main string.
4. Increment the counter for each occurrence found.
5. Continue the process until no more occurrences are found.
6. Print the number of occurrences of the substring.
3. Code Program
public class SubstringOccurrences {
public static void main(String[] args) {
// Step 1: Define the main string and the substring whose occurrences we want to count
String mainString = "abababababa";
String subString = "aba";
// Step 2: Initialize a counter to keep track of the number of occurrences
int count = 0;
int idx = 0;
// Step 3: Use a loop and the indexOf method to find the positions of the substring in the main string
while ((idx = mainString.indexOf(subString, idx)) != -1) {
// Step 4: Increment the counter for each occurrence found
count++;
idx += subString.length(); // Move to the end of the found substring
}
// Step 6: Print the number of occurrences of the substring
System.out.println("The substring '" + subString + "' occurs " + count + " times in the main string.");
}
}
Output:
The substring 'aba' occurs 5 times in the main string.
4. Step By Step Explanation
Step 1: We define the mainString in which we will search and the subString whose occurrences we want to count.
Step 2: We initialize a counter count to 0, which will keep track of the number of occurrences of the substring. We also initialize an index idx to 0.
Step 3: We use a while loop and the indexOf method to search for the substring in the main string starting from the current index idx.
Step 4: For each occurrence found, we increment the counter count by 1 and update idx to the position after the found substring to continue the search.
Step 6: Finally, we print the number of occurrences of the substring in the main string.