Find all occurrences of substring in string in Java

前端 未结 2 1722
说谎
说谎 2020-12-06 11:52

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

相关标签:
2条回答
  • 2020-12-06 11:59

    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<Integer> result = new ArrayList<Integer>();
    
    while(lastIndex != -1) {
    
        lastIndex = str.indexOf(findStr,lastIndex);
    
        if(lastIndex != -1){
            result.add(lastIndex);
            lastIndex += 1;
        }
    }
    
    0 讨论(0)
  • 2020-12-06 12:00

    You can use capturing inside a positive look-ahead to get all overlapping matches and use Matcher#start to get the indices of the captured substrings.

    As for the 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

    0 讨论(0)
提交回复
热议问题