数组元素的子串索引

4
我需要获取要搜索的数组中元素的索引:
 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));

尝试2

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

两者都没有按预期工作。


1
matches 尝试匹配整个字符串。如果您想使用 matches,则必须使用 "^" + q + ".*" 或类似的内容。(您可能还想在 q 中使用 Pattern.quote 进行包装。) - aioobe
谢谢,它适用于items[i].matches,但不适用于.indexof。 - Ravichandra
什么意思?如果你使用 temp = "Two.*" 那么应该打印出 1。不是吗?(String.indexOf 只能用于 String,而不能用于字符串列表。) - aioobe
等等,为什么不使用多维数组? - Yodism
@aioobe 谢谢,非常有用的信息。 - Ravichandra
3个回答

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);
    }
}

你的第一次尝试不起作用,因为你试图在列表中获取字符串^Two的索引,但是indexOf(String str)不接受正则表达式。
你的第二次尝试不起作用,因为matches(String regex)适用于整个字符串,而不仅仅是开头。
如果你正在使用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);

谢谢。我们能否在不使用循环的情况下获取索引? - Ravichandra
@Ravichandra 要获取索引,你需要循环。如果你使用的是Java 8,这可以隐藏在一个Stream中。 - Tunaki

0

我认为你需要实现LinearSearch来完成这个任务,但要有所改变,因为你现在是在搜索子字符串。你可以试一下这个。

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
    }
}

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

对于 try-2,您应该使用 q +"(.*)"。它将提供带有任何字符的 q 的索引。 - Santhosh Kumar
虽然这段代码可能回答了问题,但是提供关于为什么和/或如何回答问题的额外上下文可以提高其长期价值。 - ryanyuyu

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接