goat
goat

Reputation: 107

Simplify code - Checking the first character in a string to match a list of characters

So this is my code at the moment;

public static boolean isValidPiecePlacement(String piecePlacementString) {

    if (piecePlacementString.charAt(0) == 'A' || piecePlacementString.charAt(0) == 'B' ||
    piecePlacementString.charAt(0) == 'C' || piecePlacementString.charAt(0) == 'D' ||
    piecePlacementString.charAt(0) == 'E' || piecePlacementString.charAt(0) == 'F' ||
    piecePlacementString.charAt(0) == 'G'){
        return true;
    }


    return false;

It works fine, but it is not efficient. I was wondering if someone knew how to do this is a more efficient way? The code just checks if the first character is correct, which is characters from 'A-G'. It also has to return true. Thanks

Upvotes: 1

Views: 101

Answers (6)

Prerna Gandhi
Prerna Gandhi

Reputation: 1

We can use regex:

String regex = "(^[A-G].*)";
System.out.println("Adfgh".matches(regex));

Upvotes: 0

Manoj Nannapaneni
Manoj Nannapaneni

Reputation: 16

You can simply return the following:

return "ABCDEFG".indexOf(piecePlacementString.charAt(0))>-1;

Upvotes: 0

Ruslan
Ruslan

Reputation: 6290

You could use Set of correct first characters like:

Set<Character> set = Set.of('A', 'B', 'C', 'D', 'E', 'F', 'G');
return set.contains(piecePlacementString.charAt(0));

Upvotes: 0

Andrew
Andrew

Reputation: 49606

['A', 'G'] is a range of characters, so it can be simplified to

public static boolean isValidPiecePlacement(String piecePlacementString) {
    if (piecePlacementString == null || piecePlacementString.length() == 0) {
        return false;
    }

    final char firstChar = piecePlacementString.charAt(0);

    if (firstChar >= 'A' && firstChar <= 'G') {
        // make other comparisons
        return true;
    }
    return false;
}

char is an integral type, so the numerical comparison operators like >= and <= can be applied to its variables/literals.

Upvotes: 8

Darshan Mehta
Darshan Mehta

Reputation: 30819

You can use regex for this, e.g.:

String regex = "[A-G].*";
System.out.println("Asdsd".matches(regex));
System.out.println("Bsdsd".matches(regex));
System.out.println("Csdsd".matches(regex));
System.out.println("Dsdsd".matches(regex));
System.out.println("Hsdsd".matches(regex));

Upvotes: 1

QBrute
QBrute

Reputation: 4536

chars can actually be used as numeric values. Behind each char is a decimal representation according to the ASCII table.

The character A has decimal ASCII value 65, while G has value 71.

You can simplify your code to

public static boolean isValidPiecePlacement(String piecePlacementString) {
    char c = piecePlacementString.charAt(0);
    return c >= 'A' && c <= 'G';
}

Upvotes: 2

Related Questions