Nimrod
Nimrod

Reputation: 1140

How to manually lexicographically compareTo "abcd" & ""abcde" effectively

I wanted to write my own compareTo method, so I wrote this simple code:

public int myCompare(String a, String b) {
    int min = Math.min(a.length(), b.length());

    for (int i=0; i < min; i++) {
        int diff = a.charAt(i) - b.charAt(i);
        if (diff == 0) {
            continue;
        } else {
            return diff;
        }
    }
    // meaning both strings are equals so far
    if (a.length() == b.length()) {
        return 0;
    } else if (a.length() > b.length()) {
        return -1;
    } else {
        return 1;
    }
}

Well, this code is working ok, but I hate the last if/else statement- do you have any suggestions how to improve this code?

Upvotes: 1

Views: 327

Answers (1)

Peter Lawrey
Peter Lawrey

Reputation: 533680

That depends on how much of it you want to write yourself. You could use

return a.length() - b.length(); // as length is non-negative

or

return Integer.compareTo(a.length(), b.length());

In your first loop you could also write

for (int i = 0; i < a.length() && i < b.length(); i++) {
    int diff = a.charAt(i) - b.charAt(i);
    if (diff != 0)
        return diff;
}

Upvotes: 3

Related Questions