I want to check if a String contains repeated substrings.
For example, how do I check (bc)*
without using regex library in Java?
You could simply use this recursive algorithm:
public static boolean repeatedString(String str, String repeat, int lastIndex) {
int next = str.indexOf(repeat, lastIndex+repeat.length());
if(next == -1) return false;
else if(next-lastIndex == repeat.length()) return true;
else return repeatedString(str, repeat, next);
}
Call repeatedString(str, "bc", -1)
, It's essentially checking if any two occurences of repeat
are consecutive.
An easy way would be to filter through each character and check to see if it starts with the substring that you are looking for.
public static int countSubstringOccurences(String st, String substring) {
int count = 0;
for(int i = 0; i < st.length(); i++) {
if(st.substring(i).startsWith(substring)) {
count++;
}
}
return count;
}
This will method will test each substring of the given String to see if it starts with the given substring, and increase the count by one each time it finds a match.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.