如何从给定的值中找到 Java 中 STRING 数组的索引?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23160832/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 21:07:29  来源:igfitidea点击:

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

javaarraysstringposition

提问by Cyberflow

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 ?

我想知道数组中是否有用于 Java 的本机方法来获取给定值的表索引?

Let's say my table contains these strings :

假设我的表包含这些字符串:

public static final String[] TYPES = {
        "Sedan",
        "Compact",
        "Roadster",
        "Minivan",
        "SUV",
        "Convertible",
        "Cargo",
        "Others"
    };

Let's say the user has to enter the type of car and that then in the background the program takes that string and get's it's position in the array.

假设用户必须输入汽车的类型,然后程序在后台获取该字符串并获取它在数组中的位置。

So if the person enters : Sedan It should take the position 0 and store's it in the object of Cars created by my program ...

因此,如果该人输入: Sedan 它应该占据位置 0 并将其存储在我的程序创建的 Cars 对象中......

采纳答案by Anubian Noob

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 indexis the array index of your car, or -1 if it doesn't exist.

之后index是您的汽车的数组索引,如果不存在则为 -1。

回答by mok

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);

回答by Alaeddine

Try this Function :

试试这个功能:

public int indexOfArray(String input){
     for(int i=0;i<TYPES,length();i++)
       {
         if(TYPES[i].equals(input))
         {
          return i ;
         }
        }
      return -1     // if the text not found the function return -1
      }

回答by Alaeddine

Type in:

输入:

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

回答by R.W

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.

肯定会有更好的方法,但对于少量项目,这应该很快。顺便说一句,这是javascript,但几乎所有编程语言都应该使用相同的方法。

回答by Arjit

Use Arraysclass to do this

使用Arrays类来做到这一点

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

回答by Wayne

try this instead

试试这个

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

回答by Gary Davies

Testable mockable interafce

可测试的可模拟界面

public interface IArrayUtility<T> {

    int find(T[] list, T item);

}

implementation

执行

public class ArrayUtility<T> implements IArrayUtility<T> {

    @Override
    public int find(T[] array, T search) {
        if(array == null || array.length == 0 || search == null) {
            return -1;
        }

        int position = 0;

        for(T item : array) {

            if(item.equals(search)) {
                return position;
            } else {
                ++position;
            }
        }

        return -1;
    }

}

Test

测试

@Test
public void testArrayUtilityFindForExistentItemReturnsPosition() {
    // Arrange
    String search = "bus";
    String[] array = {"car", search, "motorbike"};

    // Act
    int position = arrayUtility.find(array, search);

    // Assert
    Assert.assertEquals(position, 1);
}

回答by abhishek58g

There is no native indexof method in java arrays.You will need to write your own method for this.

java 数组中没有本机 indexof 方法。您需要为此编写自己的方法。

回答by mitchell Williamson

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!

将此用作 x 最初为任意数字的方法。控制台传入的字符串 y 和 v 是要搜索的数组!

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;
}