我需要获取要搜索的数组中元素的索引:
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);
}
两者都没有按预期工作。
matches
尝试匹配整个字符串。如果您想使用matches
,则必须使用"^" + q + ".*"
或类似的内容。(您可能还想在q
中使用Pattern.quote
进行包装。) - aioobetemp = "Two.*"
那么应该打印出1
。不是吗?(String.indexOf
只能用于String
,而不能用于字符串列表。) - aioobe