使用子字符串的数组中元素的索引

Rav*_*dra 4 java regex arrays substring indexof

我需要获取要搜索的数组中元素的索引:

 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"
Run Code Online (Sandbox Code Playgroud)

我尝试了什么

尝试-1

    String temp = "^"+q;    
    System.out.println(Arrays.asList(items).indexOf(temp));
Run Code Online (Sandbox Code Playgroud)

尝试-2

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

两者都没有按预期工作.

Tun*_*aki 7

你最好这样使用startsWith(String prefix):

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

您的第一次尝试不起作用,因为您试图获取^Two列表中的String索引,但indexOf(String str)不接受正则表达式.

你的第二次尝试不起作用,因为matches(String regex)在整个String上工作,而不仅仅是在开头.

如果您使用的是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);
Run Code Online (Sandbox Code Playgroud)