something like equalsIgnoreCase while using indexOf

前端 未结 4 2018
谎友^
谎友^ 2021-01-13 05:25

I am using this code, to get the index of a String in an Array.

int n = Arrays.asList(Names).indexOf(textBox.getText());

The problem here i

4条回答
  •  遥遥无期
    2021-01-13 06:09

    You can use StringUtils class of Apache commons libraries or this If you don't want to download the library look at the source code for logic to create the method. The stackoverflow link for using StringUtils

    If you want to find the index of String from array of strings then there is another library ArrayUtils which has a method indexOf

    here's the implementation of indexOf

     public static int indexOf(Object[] array, Object objectToFind, int startIndex) {
            if (array == null) {
                return INDEX_NOT_FOUND;
            }
            if (startIndex < 0) {
                startIndex = 0;
            }
            if (objectToFind == null) {
                for (int i = startIndex; i < array.length; i++) {
                    if (array[i] == null) {
                        return i;
                    }
                }
            } else {
                for (int i = startIndex; i < array.length; i++) {
                    if (objectToFind.equals(array[i])) {
                        return i;
                    }
                }
            }
            return INDEX_NOT_FOUND;
        }
    

    since you can see that it uses .equals() I suggest you to

    1) create a custom string class

    2) add it to the array

    3) override the .equals method like this

    class StringCustom
    {
    String string;
    //implement getters and setters
    public String equals(Object o)
    {
    return this.getString().equalsIgnoreCase(((String)o).getString());
    }
    }
    

提交回复
热议问题