Index of an element in an array using a substring

I need to get the index of an element in an array to search:

 String[] items = {"One:10.1.22.33", "Two:10.1.21.23", "Three:10.1.21.33", "Four:10.1.21.23", "Five:10.1.22.23"};
 String q = "Two";  //need to find index of element starting with sub-sting "Two"

what i tried

Try-1

    String temp = "^"+q;    
    System.out.println(Arrays.asList(items).indexOf(temp));

Try-2

items[i].matches(temp)
for(int i=0;i<items.length;i++) {
    if(items[i].matches(temp)) System.out.println(i);
}

Both do not work properly.

+4
source share
3 answers

You would be better off using startsWith(String prefix)as follows:

String[] items = {"One:10.1.22.33", "Two:10.1.21.23", "Three:10.1.21.33", "Four:10.1.21.23", "Five:10.1.22.23"};
String q = "Two";  //need to find index of element starting with substring "Two"
for (int i = 0; i < items.length; i++) {
    if (items[i].startsWith(q)) {
        System.out.println(i);
    }
}

Your first attempt does not work, because you are trying to get the String index ^Twoinside your list, but indexOf(String str)not accepting a regular expression.

Your second attempt does not work, because it matches(String regex)works in the entire line, and not just in the beginning.

Java 8, , , "Two", -1, .

String[] items = {"One:10.1.22.33", "Two:10.1.21.23", "Three:10.1.21.33", "Four:10.1.21.23", "Five:10.1.22.23"};
String q = "Two";
int index = IntStream.range(0, items.length).filter(i -> items[i].startsWith(q)).findFirst().orElse(-1);
+7

, LinearSearch , substring. .

String[] items = {"One:10.1.22.33", "Two:10.1.21.23", "Three:10.1.21.33", "Four:10.1.21.23", "Five:10.1.22.23"};
String q= "Two";  //need to find index of element starting with sub-sting "Two"

for (int i = 0; 0 < items.length; i++) {
    if (items[i].startsWith(q)){
        // item found
        break;
    } else if (i == items.length) {
        // item not found
    }
}
0
String q= "Five";String pattern = q+"(.*)";
for(int i=0;i<items.length;i++)
{
if(items[i].matches(pattern))
 { 
  System.out.println(i);
 }
}
-1
source

Source: https://habr.com/ru/post/1606375/


All Articles