Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a string is startwith in an array

Tags:

java

string

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?

like image 253
Viet Avatar asked Dec 20 '25 08:12

Viet


2 Answers

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();
}
like image 144
Jon Skeet Avatar answered Dec 21 '25 23:12

Jon Skeet


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
like image 45
Ankur Singhal Avatar answered Dec 21 '25 22:12

Ankur Singhal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!