简体   繁体   中英

What's the better way to check if a String is empty than using String.trim().length() in Java 5/6?

There probably is a method to return the index of the first non-blank char in a String in Java5/6. But I cannot find it any more. A code anylizing tool says it is better than checking String.trim().length() .

I always like to use the Apache Commons StringUtils library. It has isEmpty() and is isBlank() which handles whitespace.

http://commons.apache.org/lang/api-2.5/org/apache/commons/lang/StringUtils.html

Not to mention the numerous other helpful methods in that class and the library in general.

I'd use the Guava CharMatcher class:

boolean onlyWhitespace = CharMatcher.WHITESPACE.matchesAllOf(input);

Okay guys, I have found it finally from PMD rules of InefficientEmptyStringCheck :

InefficientEmptyStringCheck:
Since: PMD 3.6
String.trim().length() is an inefficient way to check if a String is really empty, as it creates a new String object just to check its size. Consider creating a static function that loops through a string, checking Character.isWhitespace() on each character and returning false if a non-whitespace character is found.

This is only a suggestion from PMD. To adopt it or not is depending on which has priority: the efficiency of programs or the time of programmers.

Java 11 introduces the "isBlank" method. See https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/String.html#isBlank()

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

Java 6 has introduced String.isEmpty() , so you could use it in conjunction with String.trim() . You can also use regular expressions, for example using such a condition: .str.matches("\\s*") .

If you want to test, whether it only contains whitespace characters, you can use RegEx

string.matches("\\s*")

Thinks it's more efficient than trim().isEmpty(), especially if you expect whitespaces and have long Strings, though I'm not sure how much effort it takes to compile the RegEx.

If you want to test for a string that has a zero length than using isEmpty() or length() == 0 is the best way.

If you want to test if the string only contains whitespaces, then searching for the first non-whitespace character is more efficient because not intermediate object is created (as with trim() )

But in any case I too recommend Apache's commons StringUtils.isEmpty() as it nicely encapsulates all this.

There is a method in String for this exact purpose.

String emptyString = "";
emptyString.isEmpty();

This will return true.

try

  str!=null && str.trim().isEmpty()

(Best way) string.equals("")

But also,

string.isEmpty()

string.equals(null)

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