【问题标题】:Index of a element in array using substring使用子字符串对数组中的元素进行索引
【发布时间】:2015-12-03 20:36:33
【问题描述】:

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

 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"

我尝试过的

试一试

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

两者都没有按预期工作。

【问题讨论】:

  • matches 尝试匹配整个字符串。如果您想使用matches,则必须使用"^" + q + ".*" 或类似的东西。 (您可能还想将q 包装在Pattern.quote 中。)
  • 感谢它为 items[i].matches 工作,但不适用于 .indexof
  • 什么意思?如果您使用temp = "Two.*",则应打印1。不是吗? (String.indexOf 只能用于 String,而不是字符串列表。)
  • 等等,为什么不用多维数组呢?
  • @aioobe 谢谢伟大的信息

标签: java arrays regex substring indexof


【解决方案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 的索引提供任何字符
  • 虽然此代码可能会回答问题,但提供有关此代码为何和/或如何回答问题的额外上下文可提高其长期价值。
【解决方案2】:

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

【讨论】:

    【解决方案3】:

    你最好像这样使用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 要获取索引,您将不得不循环。如果您使用的是 Java 8,则可以将其隐藏在 Stream 中。
    猜你喜欢
    • 1970-01-01
    • 2015-11-25
    • 1970-01-01
    • 2015-10-22
    • 1970-01-01
    • 2021-09-27
    • 2016-09-10
    • 2022-07-10
    相关资源
    最近更新 更多