155

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:
How can I check if string contains characters & whitespace, not just whitespace?

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

Naman
  • 27,789
  • 26
  • 218
  • 353
Ankur
  • 50,282
  • 110
  • 242
  • 312
  • 3
    Be aware that there are many different definitions of whitespace: http://spreadsheets.google.com/pub?key=pd8dAQyHbdewRsnE5x5GzKQ Which do you want? Or then you say "has an alphanumeric character", which is a completely different thing. Please clarify. – Kevin Bourrillion Jul 14 '10 at 15:20
  • Apologies for the confusion ... not all whitespaces is the key- basically if it has all whitespace characters I want to exclude it, because it has no content. – Ankur Jul 14 '10 at 15:27
  • 2
    With JDK/11 you can [make use of the `String.isBlank`](https://stackoverflow.com/a/50631090/1746118) API for the same. – Naman May 31 '18 at 19:01

16 Answers16

243

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.

Carl Smotricz
  • 66,391
  • 18
  • 125
  • 167
  • 10
    FWIW: I would expect the first solution to be considerably faster. – Stephen C Jul 14 '10 at 14:29
  • 2
    @Stephen C: Absolutely! But as @Uri pointed out, I'm having to solve two different problems thanks to the ambiguity of the question :) Also, I rarely use `matches()`: for performance, I usually store the `Pattern` in a `final static`. Pays off if the same code runs frequently. – Carl Smotricz Jul 14 '10 at 14:31
  • @Carl - look out, there's one `string == null` coming! - Ouch - NPE - that hurts ;-)) – Andreas Dolk Jul 14 '10 at 14:51
  • 3
    @Andreas_D: Heh, I got my orders! The OP said he wanted to check a string or char array, he never said anything about nulls! :) \*checks the fine print in the contract\* "`null` is not a string!" – Carl Smotricz Jul 14 '10 at 15:01
  • ".*\\w.*" can be simplified to simply "\\w" to achieve the same result. – Rob Raisch May 28 '11 at 15:30
  • 1
    Also, "\\w" only matches a limited subset of non-whitespace characters rather than all non-whitespace since it refers to "word characters" defined as A-Z, a-z, 0-9, and underscore. – Rob Raisch May 28 '11 at 15:30
  • 1
    @Rob Raisch, I must object to both of your comments. Second comment first: I explicitly gave "\w" as an example checking for a particular character class, not to solve the original simpler problem. First comment: No, "\\w" will not match a series of word characters preceded, surrounded or followed by other characters, e.g. whitespace. String.matches() matches the entire string, not a subset. – Carl Smotricz Dec 04 '11 at 11:51
  • 2
    I used your_string.trim().isEmpty() and did the job for me – Neri Jul 08 '18 at 11:05
66

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

Pang
  • 9,564
  • 146
  • 81
  • 122
Chris J
  • 9,164
  • 7
  • 40
  • 39
58

Slightly shorter than what was mentioned by Carl Smotricz:

!string.trim().isEmpty();
redslime
  • 589
  • 4
  • 3
  • 11
    You young whippersnappers and your newfangled post-Java-1.6 trickery! Seriously, at least one project in my company still runs on Java 1.4 (sigh). – Carl Smotricz Dec 04 '11 at 11:54
  • Shorter? Yes. Personally, I like the more verbose coding style – Michel Mar 12 '14 at 11:34
23
StringUtils.isBlank(CharSequence)

https://commons.apache.org/proper/commons-lang/javadocs/api-release/org/apache/commons/lang3/StringUtils.html#isBlank-java.lang.CharSequence-

Pang
  • 9,564
  • 146
  • 81
  • 122
darelf
  • 4,589
  • 2
  • 16
  • 11
12

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.

Pyves
  • 6,333
  • 7
  • 41
  • 59
5

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()));
}
Andreas Dolk
  • 113,398
  • 19
  • 180
  • 268
5

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);
Arun
  • 2,312
  • 5
  • 24
  • 33
5
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.

Rob Raisch
  • 17,040
  • 4
  • 48
  • 58
  • 2
    Let try: `String year="1995"; year.matches("\\S"); will return false` So this is not correct solution. :| – Nhat Dinh May 20 '15 at 02:59
  • 6
    Nhat, you are correct though I'm at a loss to explain why. According to the Java docs, String.matches checks to see if a given string matches a regex. A little experimentation shows that this is not entirely accurate, as this function appears to match ONLY if the provided regex matches the ENTIRE string! So, changing the regex above ("\\S") to "^.*\\S.*$" will work as expected, though this behavior isn't correctly documented and appears to diverge substantially from every other implementation of string matching using Regular Expressions. – Rob Raisch May 26 '15 at 15:46
4

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()
Naman
  • 27,789
  • 26
  • 218
  • 353
4

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.

martlin
  • 158
  • 2
  • 10
1

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.

Corey Ogburn
  • 24,072
  • 31
  • 113
  • 188
  • Link in answer is dead - *404 | We're sorry, the page does not exist or is no longer available*. – Pang Jan 27 '18 at 06:35
0

Alternative:

boolean isWhiteSpaces( String s ) {
    return s != null && s.matches("\\s+");
 }
OscarRyz
  • 196,001
  • 113
  • 385
  • 569
0

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.

andreyro
  • 935
  • 12
  • 18
0
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

akakargul
  • 61
  • 7
0

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" };
}
fozzybear
  • 91
  • 9
0
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;
    }
Muhammad Zahab
  • 1,049
  • 10
  • 21