gpt4 book ai didi

java - 给定一个字符串数组,如何找出特定字符串的索引?

转载 作者:行者123 更新时间:2023-12-01 22:05:40 24 4
gpt4 key购买 nike

我有,

String[] directions = {"North", "South", "West", "East"};

不,我有一个 String s,它是这 4 个字符串文字中的任何一个。

如何获取 s 在方向上的索引?

最佳答案

可能的枚举

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

打印出:

 Direction: Ordinal
North: 0
South: 1
East: 2
West: 3

但是,细节决定成败。正如此方法的枚举 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.

关于java - 给定一个字符串数组,如何找出特定字符串的索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32854054/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com