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

前端 未结 13 2061
谎友^
谎友^ 2020-12-08 02:11

I wanted to know if there\'s a native method in array for Java to get the index of the table for a given value ?

Let\'s say my table contains these strings :

<
相关标签:
13条回答
  • 2020-12-08 02:48

    Use Arrays class to do this

    Arrays.sort(TYPES);
    int index = Arrays.binarySearch(TYPES, "Sedan");
    
    0 讨论(0)
  • 2020-12-08 02:51

    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;
    }
    
    0 讨论(0)
  • 2020-12-08 02:51

    Use this as a method with x being any number initially. The string y being passed in by console and v is the array to search!

    public static int getIndex(int x, String y, String[]v){
        for(int m = 0; m < v.length; m++){
            if (v[m].equalsIgnoreCase(y)){
                x = m;
            }
        }
        return x;
    }
    
    0 讨论(0)
  • 2020-12-08 02:52
    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);
    
    0 讨论(0)
  • 2020-12-08 02:53

    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);
    
    0 讨论(0)
  • 2020-12-08 02:55

    An easy way would be to iterate over the items in the array in a loop.

    for (var i = 0; i < arrayLength; i++) {
     // (string) Compare the given string with myArray[i]
     // if it matches store/save i and exit the loop.
    }
    

    There would definitely be better ways but for small number of items this should be blazing fast. Btw this is javascript but same method should work in almost every programming language.

    0 讨论(0)
提交回复
热议问题