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 ?
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:
Or taking a cue from String.trim’s implementation, you could use character comparison rather than Character.isWhitespace():
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.