How do I check that a Java String is not all whitespaces?

JavaStringWhitespace

Java Problem Overview


I want to check that Java String or character array is not just made up of whitespaces, using Java?

This is a very similar question except it's Javascript:
https://stackoverflow.com/questions/2031085/check-if-string-contains-characters-whitespaces-not-only-whitespaces">https://stackoverflow.com/questions/2031085/check-if-string-contains-characters-whitespaces-not-only-whitespaces</a>

EDIT: I removed the bit about alphanumeric characters, so it makes more sense.

Java Solutions


Solution 1 - Java

Shortest solution I can think of:

if (string.trim().length() > 0) ...

This only checks for (non) white space. If you want to check for particular character classes, you need to use the mighty match() with a regexp such as:

if (string.matches(".*\\w.*")) ...

...which checks for at least one (ASCII) alphanumeric character.

Solution 2 - Java

I would use the Apache Commons Lang library. It has a class called StringUtils that is useful for all sorts of String operations. For checking if a String is not all whitespaces, you can use the following:

StringUtils.isBlank(<your string>)

Here is the reference: StringUtils.isBlank

Solution 3 - Java

Slightly shorter than what was mentioned by Carl Smotricz:

!string.trim().isEmpty();

Solution 4 - Java

Solution 5 - Java

If you are using Java 11 or more recent, the new isBlank string method will come in handy:

!s.isBlank();

If you are using Java 8, 9 or 10, you could build a simple stream to check that a string is not whitespace only:

!s.chars().allMatch(Character::isWhitespace));

In addition to not requiring any third-party libraries such as Apache Commons Lang, these solutions have the advantage of handling any white space character, and not just plain ' ' spaces as would a trim-based solution suggested in many other answers. You can refer to the Javadocs for an exhaustive list of all supported white space types. Note that empty strings are also covered in both cases.

Solution 6 - Java

This answer focusses more on the sidenote "i.e. has at least one alphanumeric character". Besides that, it doesn't add too much to the other (earlier) solution, except that it doesn't hurt you with NPE in case the String is null.

We want false if (1) s is null or (2) s is empty or (3) s only contains whitechars.

public static boolean containsNonWhitespaceChar(String s) {
  return !((s == null) || "".equals(s.trim()));
}

Solution 7 - Java

if(target.matches("\\S")) 
    // then string contains at least one non-whitespace character

Note use of back-slash cap-S, meaning "non-whitespace char"

I'd wager this is the simplest (and perhaps the fastest?) solution.

Solution 8 - Java

If you are only checking for whitespace and don't care about null then you can use org.apache.commons.lang.StringUtils.isWhitespace(String str),

StringUtils.isWhitespace(String str);

(Checks if the String contains only whitespace.)

If you also want to check for null(including whitespace) then

StringUtils.isBlank(String str);

Solution 9 - Java

Just an performance comparement on openjdk 13, Windows 10. For each of theese texts:

"abcd"
"    "
" \r\n\t"
" ab "
" \n\n\r\t   \n\r\t\t\t   \r\n\r\n\r\t \t\t\t\r\n\n"
"lorem ipsum dolor sit amet  consectetur adipisici elit"
"1234657891234567891324569871234567891326987132654798"

executed one of following tests:

// trim + empty
input.trim().isEmpty()

// simple match
input.matches("\\S")

// match with precompiled pattern
final Pattern PATTERN = Pattern.compile("\\S");
PATTERN.matcher(input).matches()

// java 11's isBlank
input.isBlank()

each 10.000.000 times.

The results:

METHOD    min   max   note
trim:      18   313   much slower if text not trimmed
match:   1799  2010   
pattern:  571   662   
isBlank:   60   338   faster the earlier hits the first non-whitespace character

Quite surprisingly the trim+empty is the fastest. Even if it needs to construct the trimmed text. Still faster then simple for-loop looking for one single non-whitespaced character...

EDIT: The longer text, the more numbers differs. Trim of long text takes longer time than just simple loop. However, the regexs are still the slowest solution.

Solution 10 - Java

With Java-11+, you can make use of the String.isBlank API to check if the given string is not all made up of whitespace -

String str1 = "    ";
System.out.println(str1.isBlank()); // made up of all whitespaces, prints true

String str2 = "    a";
System.out.println(str2.isBlank()); // prints false

The javadoc for the same is :

/**
 * Returns {@code true} if the string is empty or contains only
 * {@link Character#isWhitespace(int) white space} codepoints,
 * otherwise {@code false}.
 *
 * @return {@code true} if the string is empty or contains only
 *         {@link Character#isWhitespace(int) white space} codepoints,
 *         otherwise {@code false}
 *
 * @since 11
 */
public boolean isBlank()

Solution 11 - Java

The trim method should work great for you.

http://download.oracle.com/docs/cd/E17476_01/javase/1.4.2/docs/api/java/lang/String.html#trim()

> Returns a copy of the string, with > leading and trailing whitespace > omitted. If this String object > represents an empty character > sequence, or the first and last > characters of character sequence > represented by this String object both > have codes greater than '\u0020' (the > space character), then a reference to > this String object is returned. > > Otherwise, if there is no character > with a code greater than '\u0020' in > the string, then a new String object > representing an empty string is > created and returned. > > Otherwise, let k be the index of the > first character in the string whose > code is greater than '\u0020', and let > m be the index of the last character > in the string whose code is greater > than '\u0020'. A new String object is > created, representing the substring of > this string that begins with the > character at index k and ends with the > character at index m-that is, the > result of this.substring(k, m+1). > > This method may be used to trim > whitespace from the beginning and end > of a string; in fact, it trims all > ASCII control characters as well. > > Returns: A copy of this string with > leading and trailing white space > removed, or this string if it has no > leading or trailing white space.leading or trailing white space.

You could trim and then compare to an empty string or possibly check the length for 0.

Solution 12 - Java

Alternative:

boolean isWhiteSpaces( String s ) {
    return s != null && s.matches("\\s+");
 }

Solution 13 - Java

trim() and other mentioned regular expression do not work for all types of whitespaces

i.e: Unicode Character 'LINE SEPARATOR' http://www.fileformat.info/info/unicode/char/2028/index.htm

Java functions Character.isWhitespace() covers all situations.

That is why already mentioned solution StringUtils.isWhitespace( String ) /or StringUtils.isBlank(String) should be used.

Solution 14 - Java

StringUtils.isEmptyOrWhitespaceOnly(<your string>)

will check :

  • is it null
  • is it only space
  • is it empty string ""

https://www.programcreek.com/java-api-examples/?class=com.mysql.jdbc.StringUtils&method=isEmptyOrWhitespaceOnly

Solution 15 - Java

While personally I would be preferring !str.isBlank(), as others already suggested (or str -> !str.isBlank() as a Predicate), a more modern and efficient version of the str.trim() approach mentioned above, would be using str.strip() - considering nulls as "whitespace":

if (str != null && str.strip().length() > 0) {...}

For example as Predicate, for use with streams, e. g. in a unit test:

@Test
public void anyNonEmptyStrippedTest() {
    String[] strings = null;
    Predicate<String> isNonEmptyStripped = str -> str != null && str.strip().length() > 0;
    assertTrue(Optional.ofNullable(strings).map(arr -> Stream.of(arr).noneMatch(isNonEmptyStripped)).orElse(true));
    strings = new String[] { null, "", " ", "\\n", "\\t", "\\r" };
    assertTrue(Optional.ofNullable(strings).map(arr -> Stream.of(arr).anyMatch(isNonEmptyStripped)).orElse(true));
    strings = new String[] { null, "", " ", "\\n", "\\t", "\\r", "test" };
}

Solution 16 - Java

public static boolean isStringBlank(final CharSequence cs) {
        int strLen;
        if (cs == null || (strLen = cs.length()) == 0) {
            return true;
        }
        for (int i = 0; i < strLen; i++) {
            if (!Character.isWhitespace(cs.charAt(i))) {
                return false;
            }
        }
        return true;
    }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAnkurView Question on Stackoverflow
Solution 1 - JavaCarl SmotriczView Answer on Stackoverflow
Solution 2 - JavaChris JView Answer on Stackoverflow
Solution 3 - JavaredslimeView Answer on Stackoverflow
Solution 4 - JavadarelfView Answer on Stackoverflow
Solution 5 - JavaPyvesView Answer on Stackoverflow
Solution 6 - JavaAndreas DolkView Answer on Stackoverflow
Solution 7 - JavaRob RaischView Answer on Stackoverflow
Solution 8 - JavaArunView Answer on Stackoverflow
Solution 9 - JavamartlinView Answer on Stackoverflow
Solution 10 - JavaNamanView Answer on Stackoverflow
Solution 11 - JavaCorey OgburnView Answer on Stackoverflow
Solution 12 - JavaOscarRyzView Answer on Stackoverflow
Solution 13 - JavaandreyroView Answer on Stackoverflow
Solution 14 - JavaakakargulView Answer on Stackoverflow
Solution 15 - JavafozzybearView Answer on Stackoverflow
Solution 16 - JavaMuhammad Zahab Ahmad KhanView Answer on Stackoverflow