gpt4 book ai didi

java - 检查数组中的字符串是否以开头开头

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

String[] directions = {"UP","DOWN","RIGHT","LEFT"};
String input = "DOWN 123 test";

有没有一种方法可以检查输入字符串是否开始方向上有一个值不使用分割输入值?

最佳答案

当然 - 只需迭代所有方向即可:

private static final String[] DIRECTIONS = {"UP","DOWN","RIGHT","LEFT"};

public static String getDirectionPrefix(String input) {
for (String direction : DIRECTIONS) {
if (input.startsWith(direction)) {
return direction;
}
}
return null;
}

或者使用 Java 8 的流:

private static final List<String> DIRECTIONS = Arrays.asList("UP","DOWN","RIGHT","LEFT");

public static Optional<String> getDirectionPrefix(String input) {
return DIRECTIONS.stream().filter(d -> input.startsWith(d)).findFirst();
}

关于java - 检查数组中的字符串是否以开头开头,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34988032/

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