Pages

Find repeated substring in given string

Find repeated substring in a given string

  • We can find the count of a substring in a given string by using the indexOf() method, StringUtils, patterns, and split method.
Program to find substring in a given string:
import java.util.regex.*;
import org.apache.commons.lang3.StringUtils;
public class countWord {
public static void main(String[] args) {
String str = "whatat at dat";
String find = "at";


int index = 0;
int count5 = 0;
while (true) {
index = str.indexOf(find, index);
if (index != -1) {
count5++;
index += find.length();
} else {
break;
}
}
System.out.println("Find string in given string using indexOf()=" + count5);


Matcher m = Pattern.compile(find).matcher(str);

int count1 = 0;
while (m.find()) {
count1++;
}
System.out.println("Find string in given string using pattern=" + count1);

int count2 = StringUtils.countMatches(str, find);
System.out.println("Find string in given string using StringUtils=" + count2);


Pattern pattern = Pattern.compile("[^at]*at");
Matcher matcher = pattern.matcher(str);
int count = 0;
while (matcher.find()) {
count++;
}
System.out.println("Find string in given string using patterns using regular expression=" + count);


int count4 = str.split(find, -1).length - 1;
//int count4=str.split(find).length - 1;
System.out.println("Find string in given string using split method=" + count4);

}
}
Output:
repeated substring in given string
Please comment below for feedback or ask questions.

No comments:

Post a Comment

Please comment below to feedback or ask questions.