简体   繁体   中英

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 ?

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;
}

You can always see c#'s implementation through .net reflector or other decompiler:

public static bool IsNullOrEmpty(string value)
{
  if (value != null)
    return value.Length == 0;
  else
    return true;
}

and

public static bool IsNullOrWhiteSpace(string value)
{
  if (value == null)
    return true;
  for (int index = 0; index < value.Length; ++index)
  {
    if (!char.IsWhiteSpace(value[index]))
      return false;
  }
  return true;
}

you can try like this

import org.apache.commons.lang.StringUtils;

public class CheckEmptyStringExample 
{  
  public static void main(String[] args)
  {
     String string1 = "";
     String string2 = "\t\r\n";
     String string3 = " ";
     String string4 = null;
     String string5 = "Hi"; 
     System.out.println("\nString one is empty? " + StringUtils.isBlank(string1));
     System.out.println("String one is not empty? " + StringUtils.isNotBlank(string1));
     System.out.println("\nString two is empty? " +  StringUtils.isBlank(string2));
     System.out.println("String two is not empty?" + StringUtils.isNotBlank(string2));
     System.out.println("\nString three is empty?" + StringUtils.isBlank(string3));
     System.out.println("String three is not empty?" + StringUtils.isNotBlank(string3));
     System.out.println("\nString four is empty?" +  StringUtils.isBlank(string4));
     System.out.println("String four is not empty?" + StringUtils.isNotBlank(string4));
     System.out.println("\nString five is empty?" + StringUtils.isBlank(string5));
     System.out.println("String five is not empty?" + StringUtils.isNotBlank(string5)); 
  }
}

看看apache commons lang中的StringUtils类。

如果您导入com.google.common.base.Strings ,则会有Strings.isNullOrEmpty()

isNullOrEmpty(@Nullable String string)

Apache Commons Lang has a vary handy set of utilities for strings: http://commons.apache.org/lang/api-release/org/apache/commons/lang3/StringUtils.html

Of course your implementation can suffice if you don't want to bother with dependencies.

apache.commons.lang.StringUtils is the answer.

isBlank()

isEmpty()

This should be much simpler and easy to understand.

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

public static boolean isNullOrWhitespace(String s) {
    return isNullOrEmpty(s) ? true : isNullOrEmpty(s.trim());
}

In JDK11 the String class has an isBlank method which:

Returns true if the string is empty or contains only white space codepoints, otherwise false.

Although it doesn't check for nullity it's certainly closer to C#'s string.IsNullOrWhiteSpace .

You could now do:

var isNullOrWhiteSpace = str == null || str.isBlank();

or create a helper method:

public static boolean isNullOrWhitespace(String s) { return s == null || str.isBlank(); }

for isnullorempty: return a == null || a.length == 0;
for isnullorwhitespace you have to check every single character until you find a non whitespace one (ascii or unicode)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM