1

I have a String for example

String value1 = "12345 abc 123 def 123";

and another one to be searched on it

String value2 ="123";

for example.

How can I return all the indices the 2nd string appears on the first? From what I've searched, indexOf and lastIndexOf searches the string for the first and last index of the specified string.

5 Answers 5

6

Use the optional parameter of indexOf.

List<Integer> indexes = new ArrayList<>();
for (int idx = haystack.indexOf(needle);
     idx != -1;
     idx = haystack.indexOf(needle, idx + 1)) {
  indexes.add(idx);
}
Sign up to request clarification or add additional context in comments.

Comments

3

Use indexOf(String str, int fromIndex)) in a loop.

Comments

3

Use Regex it is better

class Test {
    public static void main(String[] args) {
        String value1= "12345 abc 123 def 123";
        Pattern pattern = Pattern.compile("123");
        Matcher  matcher = pattern.matcher(value1);

        int count = 0;
        while (matcher.find()){
            count++;
}

        System.out.println(count);   
    }
}

2 Comments

Regex searches are for regular expressions, not literal strings. Escape the input or expect problems with "regexy" needles
Also in case of 12121 haystack and 121 needle, regex will return only 1 match, while there are 2 overlapping matches.
2

Try Regexes with Pattern and Matcher. Then you can get the start indices with matcher.start(), the end indices (exclusive) with matcher.end().

String value1 = "12345 abc 123 def 123";
String value2 = "123";
Pattern pattern = Pattern.compile(value2);
Matcher matcher = pattern.matcher(value1);

while (matcher.find()){
    System.out.println("Start: " + matcher.start() + " -- End: " + matcher.end());
}

This will give you as output:

Start: 0 -- End: 3
Start: 10 -- End: 13
Start: 18 -- End: 21

Comments

1

You will need to implement this function yourself. You could use something like:

package com.example.stringutils;
import java.util.ArrayList;

public class Util {
/** Return a list of all the indexes of the 'key' string that occur in the 
 * 'arbitrary' string. If there are none an empty list is returned.
 * 
 * @param key
 * @param arbitrary
 * @return
 */
    private static ArrayList<Integer> allIndexesOf(String key, String arbitrary) {
        ArrayList<Integer> result = new ArrayList<Integer>();
        if (key == null |  key.length() == 0 | arbitrary == null | arbitrary.length()<key.length()) {
            return result;
        }

        int loc = -1;
        while ((loc = arbitrary.indexOf(key, loc+1)) > -1) {
            result.add(loc);
        }
        return result;
    }
}

You may want to see if regular expressions actually perform faster (fewer code lines aren't always faster, just simpler "code").

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.