Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find index of STRING array in Java from a given value?

People also ask

How do you find the index of a string in an array?

To find the position of an element in an array, you use the indexOf() method. This method returns the index of the first occurrence the element that you want to find, or -1 if the element is not found. The following illustrates the syntax of the indexOf() method.

How do you get the index of an item in an array Java?

ArrayUtils. indexOf(array, element) method finds the index of element in array and returns the index.

Can I access index from string Java?

Java String indexOf() MethodThe indexOf() method returns the position of the first occurrence of specified character(s) in a string. Tip: Use the lastIndexOf method to return the position of the last occurrence of specified character(s) in a string.

Can you index an array with string?

Javascript arrays cannot have "string indexes". A Javascript Array is exclusively numerically indexed. When you set a "string index", you're setting a property of the object.


Type in:

Arrays.asList(TYPES).indexOf("Sedan");

String carName = // insert code here
int index = -1;
for (int i=0;i<TYPES.length;i++) {
    if (TYPES[i].equals(carName)) {
        index = i;
        break;
    }
}

After this index is the array index of your car, or -1 if it doesn't exist.


for (int i = 0; i < Types.length; i++) {
    if(TYPES[i].equals(userString)){
        return i;
    }
}
return -1;//not found

You can do this too:

return Arrays.asList(Types).indexOf(userSTring);

I had an array of all English words. My array has unique items. But using…

Arrays.asList(TYPES).indexOf(myString);

…always gave me indexOutOfBoundException.

So, I tried:

Arrays.asList(TYPES).lastIndexOf(myString);

And, it worked. If your arrays don't have same item twice, you can use:

Arrays.asList(TYPES).lastIndexOf(myString);

Use Arrays class to do this

Arrays.sort(TYPES);
int index = Arrays.binarySearch(TYPES, "Sedan");

try this instead

org.apache.commons.lang.ArrayUtils.indexOf(array, value);

No built-in method. But you can implement one easily:

public static int getIndexOf(String[] strings, String item) {
    for (int i = 0; i < strings.length; i++) {
        if (item.equals(strings[i])) return i;
    }
    return -1;
}