Find all occurrences of a substring in a string in Java

I am trying to find all occurrences of a substring in a string in Java.

For example: the search for "ababsdfasdfhelloasdf" for "asdf" will return [8.17], since there are 2 asdfs, one at position 8 and one at 17. Searching for "aaaaaa" for "aa" will return [0,1,2, 3,4], because there is aa in positions 0,1,2,3 and 4.

I tried this:

public List<Integer> findSubstrings(String inwords, String inword) { String copyOfWords = inwords; List<Integer> indicesOfWord = new ArrayList<Integer>(); int currentStartIndex = niwords.indexOf(inword); int indexat = 0; System.out.println(currentStartIndex); while (cthing1 > 0) { indicesOfWord.add(currentStartIndex+indexat); System.out.println(currentStartIndex); System.out.println(indicesOfWord); indexat += cthing1; copyOfWords = copyOfWords.substring(cthing1); System.out.println(copyOfWords); cthing1 = copyOfWords.indexOf(inword); } 

This problem can be solved in Python as follows:

 indices = [m.start() for m in re.finditer(word, a.lower())] 

where "word" is the word I'm looking for, and "a" is the string I'm looking for.

How can I achieve this in Java?

+6
source share
2 answers

You can use capture inside a positive appearance to get all matching matches and use Matcher#start to get the indexes of the captured substrings.

Regarding regex , it will look like

 (?=(aa)) 

In Java code:

 String s = "aaaaaa"; Matcher m = Pattern.compile("(?=(aa))").matcher(s); List<Integer> pos = new ArrayList<Integer>(); while (m.find()) { pos.add(m.start()); } System.out.println(pos); 

Result:

 [0, 1, 2, 3, 4] 

See IDEONE Demo

+5
source

Using regex is certainly too hard a solution for finding substrings, and it will be especially problematic if your substring contains special regular characters such as . . Here is a solution adapted from this answer :

 String str = "helloslkhellodjladfjhello"; String findStr = "hello"; int lastIndex = 0; List<Integer> result = new ArrayList<Integer>(); while(lastIndex != -1) { lastIndex = str.indexOf(findStr,lastIndex); if(lastIndex != -1){ result.add(lastIndex); lastIndex += 1; } } 
0
source

All Articles