Count number of occurrences of substring in a string
There is no direct API method present in the String class which can count the number of occurrence of a substring in another string and return the count. But there are other API methods which can help in counting the number of times one string occurs in other string.
The following code does the job of counting the search string in parent string in Java. The output also shows the exact count.
package com.example;
/** This class is a demo for Java Tutorial on how to count substring occurrences in Java
*
* @author Extreme Java
*
*/
public class Test {
/** This method shows how to count occurrence of substring in parent string in Java
* @param args
*/
public static void main(String[] args) {
String str1 = new String("Hello World Hello Hello Hello HelloHelloHello");
String strTemp="";
String searchString = "Hello";
int count=0;
while(!(strTemp = str1.replaceFirst(searchString, "")).equals(str1)) {
str1 = strTemp;
count++;
}
System.out.println(count);
}
}
output:
7
In the above program, we are using the replaceFirst and incrementing the count if the replace operation was successful. If there is not change in the string on performing the replace operation then the program exits after printing the count on the console.
No comments:
Post a Comment