aleroot aleroot - 3 months ago 105
C# Question

Java equivalent of c# String.IsNullOrEmpty() and String.IsNullOrWhiteSpace()

Working in c# i've found very useful two static methods of the String class :



i can't find a valid surrogate in Java, is there something similar ?

Actually i have translated the two methods in this way :

public static boolean isNullOrEmpty(String a) {
return a == null || a.isEmpty();
}

public static boolean isNullOrWhiteSpace(String a) {
return a == null || (a.length() > 0 && a.trim().length() <= 0);
}


Is this the best way to translate these methods in Java ?
What is the best way to translate these two methods in Java ?

Answer

I would prefer not to use String.trim to check for existence of whitespace. It is doing more work than you need, since it checks both ends of the string (even if non-whitespace was found at the other end) AND it returns a new String object. So I would prefer to implement a method to check for whitespace only.

So my suggestion (if implementing yourself) would be as follows:

public static boolean isNullOrEmpty(String s) {
    return s == null || s.length() == 0;
}

public static boolean isNullOrWhitespace(String s) {
    return s == null || isWhitespace(s);

}
private static boolean isWhitespace(String s) {
    int length = s.length();
    if (length > 0) {
        for (int i = 0; i < length; i++) {
            if (!Character.isWhitespace(s.charAt(i))) {
                return false;
            }
        }
        return true;
    }
    return false;
}

Or taking a cue from String.trim's implementation, you could use character comparison rather than Character.isWhitespace():

// checking for whitespace like String.trim() does
private static boolean isWhitespace(String s) {
    int length = s.length();
    if (length > 0) {
        for (int i = 0; i < length; i++) {
            if (s.charAt(i) > ' ') {
                return false;
            }
        }
        return true;
    }
    return false;
}

Finally, I'd consider checking both ends of the string in each iteration, stepping inwards. This would minimize the number of iterations needed to get the answer, regardless of whether whitespace exists at the front or the end of the string.

private static boolean isWhitespace(String s) {
    int length = s.length();
    if (length > 0) {
        for (int start = 0, middle = length / 2, end = length - 1; start <= middle; start++, end--) {
            if (s.charAt(start) > ' ' || s.charAt(end) > ' ') {
                return false;
            }
        }
        return true;
    }
    return false;
}
Comments