Reputation: 2352
I need to get the index of an element in array to be searched:
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));
Try-2
items[i].matches(temp)
for(int i=0;i<items.length;i++) {
if(items[i].matches(temp)) System.out.println(i);
}
Both are not working as expected.
Upvotes: 4
Views: 1678
Reputation: 1
String q= "Five";String pattern = q+"(.*)";
for(int i=0;i<items.length;i++)
{
if(items[i].matches(pattern))
{
System.out.println(i);
}
}
Upvotes: -1
Reputation: 247
I think you will need to implement LinearSearch
for this but with a twist, you were searching for substring
. You can try this.
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
}
}
Upvotes: 0
Reputation: 137319
You would be better off using startsWith(String prefix)
like this:
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);
}
}
Your first try does not work because you are trying to get the index of the String ^Two
inside your list, but indexOf(String str)
does not accept regular expression.
Your second try does not work because matches(String regex)
works on the entire String, not just on the beginning.
If you are using Java 8, you could write the following code which returns the index of the first item beginning with "Two"
, or -1 if none was found.
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);
Upvotes: 7