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

时间:2015-09-08 08:39:49

标签: java arrays regex 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"

我尝试了什么

尝试-1

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

尝试-2

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

两者都没有按预期工作。

3 个答案:

答案 0 :(得分:7)

最好像这样使用startsWith(String prefix)

ServletRequest/HttpSession/HttpRequest/other

您的第一次尝试不起作用,因为您试图获取列表中的字符串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); } } 的索引,但indexOf(String str)不接受正则表达式。

你的第二次尝试不起作用,因为matches(String regex)适用于整个字符串,而不仅仅是在开头。

如果您使用的是Java 8,则可以编写以下代码,该代码返回以^Two开头的第一个项的索引,如果没有找到则返回-1。

"Two"

答案 1 :(得分:0)

我认为您需要为此实施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
    }
}

答案 2 :(得分:-1)

String q= "Five";String pattern = q+"(.*)";
for(int i=0;i<items.length;i++)
{
if(items[i].matches(pattern))
 { 
  System.out.println(i);
 }
}