[英]Given an array of Strings, how to find out the index of a particular String?
I have, 我有,
String[] directions = {"North", "South", "West", "East"};
Not, I have a String s which is any one of those 4 String literals. 不,我有一个String,它是这4个String文字中的任何一个。
How do I get the index of s in directions? 如何获得s的方向索引?
A possible enum 可能的枚举
public enum Direction {
NORTH("North"), SOUTH("South"), EAST("East"), WEST("West");
private String text;
private Direction(String text) {
this.text = text;
}
public String getText() {
return text;
}
}
public class TestDirection {
public static void main(String[] args) {
System.out.printf("%10s: %-4s%n", "Direction", "Ordinal");
for (Direction dir : Direction.values()) {
System.out.printf("%10s: %-4d%n", dir.getText(), dir.ordinal());
}
}
}
Which prints out: 打印出:
Direction: Ordinal
North: 0
South: 1
East: 2
West: 3
but again, the devil is in the details. 但同样,细节决定成败。 As the enum API for this method states: 如该方法的枚举API所述:
Returns the ordinal of this enumeration constant (its position in its enum declaration, where the initial constant is assigned an ordinal of zero). 返回此枚举常量的序数(其在枚举声明中的位置,其中初始常量的序数为零)。 Most programmers will have no use for this method. 大多数程序员都不会使用这种方法。 It is designed for use by sophisticated enum-based data structures, such as EnumSet and EnumMap. 它设计用于复杂的基于枚举的数据结构,例如EnumSet和EnumMap。
You can achieve this using a for loop as well.. 您也可以使用for循环来实现。
int i, index;
for i = 0; i < directions.lenght()-1; i++{
if(s.equals(directions[i]){
index = i;
break;
}
}
Try this simple snippet: 试试这个简单的代码片段:
String[] directions = {"North", "South", "West", "East"};
int directionIndex = Arrays.asList(directions).indexOf("West");
This will give you the index of any string within the array or returns -1
if it is absent. 这将为您提供数组中任何字符串的索引,如果不存在则返回-1
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.