How to check empty space in java

String selectedVal = "";

for (SelectItem item : filterItems) {
                selectedVal = item.getValue().toString();
                break;
            }

I get selectedVal = "" how to check this empty space in java.

I tried using if (! SelectedVal.equals ("") and if (! SelectedVal.isEmpty ()), but the condition becomes true. How to check more than one empty space?

+3
source share
8 answers

You can customize trim()your string before checking withisEmpty()

boolean isEmpty = myString.trim().isEmpty();

Beware isEmpty()it is only available with Java SE 6


Resources:

+8
source

I use this all the time:

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

Returns trueonly for zero, empty string or space.

+8
source

, ( ..), Apache commons lang StringUtils.isEmpty().

Google Guava Strings. ( ..). , , , .

+2

, , . util/BagOTricks.java . .

+1

boolean isEmpty = myString.toString(). trim(). isEmpty()

+1

Java, \s .

:

 /**
   * Helper function for making null strings safe for comparisons, etc.
   *
   * @return (s == null) ? "" : s;
   */
  public static String makeSafe(String s) {
    return (s == null) ? "" : s;
  }

/**
   * Helper function for null, empty, and whitespace string testing.
   *
   * @return true if s == null or s.equals("") or s contains only whitespace
   *         characters.
   */
  public static boolean isEmptyOrWhitespace(String s) {
    s = makeSafe(s);
    for (int i = 0, n = s.length(); i < n; i++) {
      if (!Character.isWhitespace(s.charAt(i))) {
        return false;
      }
    }
    return true;
  }
0

:

public boolean isNullOrEmpty(String s) {
    return s == null || s.trim().isEmpty();
}

true, null / .

0

Using the Apache Commons Lang library, you can use StringUtils.isEmpty()to check if a string is empty ("") or zero, and StringUtils.isBlank()to check if a string is whitespace, empty ("") or zero.

Please note the differences:

IsEmpty ()

StringUtils.isEmpty(null)      = true
StringUtils.isEmpty("")        = true
StringUtils.isEmpty(" ")       = false
StringUtils.isEmpty("bob")     = false
StringUtils.isEmpty("  bob  ") = false

ISBLANK ()

StringUtils.isBlank(null)      = true
StringUtils.isBlank("")        = true
StringUtils.isBlank(" ")       = true
StringUtils.isBlank("bob")     = false
StringUtils.isBlank("  bob  ") = false
0
source

Source: https://habr.com/ru/post/1765497/


All Articles