I\'m trying to find all occurrences of a substring in a string in Java.
For example: searching \"ababsdfasdfhelloasdf\" for \"asdf\" would return [8,17] since there
Using a regex is definitely an overly heavy solution for finding substrings, and it'll especially be a problem if your substring contains special regex characters like .
. Here's a solution adapted from this answer:
String str = "helloslkhellodjladfjhello";
String findStr = "hello";
int lastIndex = 0;
List result = new ArrayList();
while(lastIndex != -1) {
lastIndex = str.indexOf(findStr,lastIndex);
if(lastIndex != -1){
result.add(lastIndex);
lastIndex += 1;
}
}