String[] directions = {"UP","DOWN","RIGHT","LEFT"};
String input = "DOWN 123 test";
Is there a way to check the input string is startwith one value in directions without using split input value?
Sure - just iterate over all the directions:
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;
}
Or using Java 8's streams:
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();
}
Iterate through the String array and use String startsWith function.
public static void main(String[] args) {
String[] directions = { "UP", "DOWN", "RIGHT", "LEFT" };
String input = "DOWN 123 test";
for (String s : directions) {
if (input.startsWith(s)) {
System.out.println("Yes - "+s);
break;
} else {
System.out.println("no - "+s);
}
}
}
output
no - UP
Yes - DOWN
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With