Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'Placeholder' character to avoid positive comparison?

I am working through the CodingBat exercises for Java. I came across the following question:

Given 2 arrays that are the same length containing strings, compare the 1st string in one array to the 1st string in the other array, the 2nd to the 2nd and so on. Count the number of times that the 2 strings are non-empty and start with the same char. The strings may be any length, including 0.

My code is this:

public int matchUp(String[] a, String[] b){

    int count = 0;

    for (int i = 0; i < a.length; i++) {
        String firstLetterA = a[i].length() == 0
                            ? "ê"
                            : a[i].substring(0, 1);
        String firstLetterB = b[i].length() == 0
                            ? "é"
                            : b[i].substring(0, 1);

        if (firstLetterA.equals(firstLetterB)) {
            count++;
        }
    }
    return count;
}

My question is: Which 'placeholder' character would be considered good practice to use to avoid unwanted comparison between firstLetterA and firstLetterB?

In this case, I have simply assigned two differing letters that are seldom used (at least, in English). I tried just using '' (an empty character, not a space) but of course, they match each other. I also tried using null for both, because I assumed it could not be positively compared, but that causes problems too.

like image 696
alanbuchanan Avatar asked Apr 21 '15 15:04

alanbuchanan


1 Answers

A good practice — IMO — is to extend if condition and not to use any dummy characters at all:

for (int i = 0; i < a.length; i++) {
    if (!a[i].isEmpty() && !b[i].isEmpty() && a[i].charAt(0) == b[i].charAt(0)) {
        count++;
    }
}
like image 164
Alex Shesterov Avatar answered Oct 16 '22 19:10

Alex Shesterov