Search code examples
javaarraysindexof

Java - find indexof for part of a needle in array haystack


I am trying to find what array index position contains part of a string.

FullDirPrt = "a1a" "b2b" "c3c"

String doT ="b2";
int DotPos = Arrays.asList(FullDirPrt).indexOf(doT);

If I search for b2b it returns indexOf. If I search for only b2, it returns -1.


Solution

  • You have to check each item in the array individually, as each array item is a separate string:

    String[] full = { "a1a", "b2b", "c3c" };
    String doT = "b2";
    
    for(int i = 0; i < full.length; i++) {
        if(full[i].contains(doT)) {
            System.out.println("Found item at index " + i);
        }
    }