简体   繁体   中英

Python “if string” expression in Java

In Python one can write if "string" to test if a string is blank or contains all white-space characters.

if "somestring":
    print(True)
else:
    print(False)

Output: True

if "":
    print(True)
else:
    print(False)

Output: False

How could this easily be done in Java?

One could do the following, but the statement would evaluate to false if someString contained any white-space characters:

if( someString.equals("") {
    System.out.println(true);
} else {
    System.out.println(false);
}

I think the closest to your answer is: someString.trim().isEmpty()


Edit: Thank to @user1886323 , you should also check for null . Actually, it is not a good idea (like myself) to reinvent the wheel.

If you need to know exactly what did they do in the Apache Commons StringUtils, you can check here here (from line 296).

The Apache Commons StringUtils class contains helper methods for this, such as isEmpty(), isBlank(), isNotEmpty() and isNotBlank(). For example:

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

If you are unwilling/unable to add a dependency on this library then you can copy the source into your own project as it is open source.

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