Java如何检查字符串是否为空?
package org.nhooo.example.commons.lang; import org.apache.commons.lang3.StringUtils; public class EmptyStringCheckDemo { public static void main(String[] args) { //创建一些变量来保存一些空字符串,仅包含 //空白和单词。 String one = ""; String two = "\t\r\n"; String three = " "; String four = null; String five = "four four two"; //我们可以使用StringUtils类来检查字符串是否为空 //使用StringUtils.isBlank()方法。如果此方法将返回true //测试的字符串为空,仅包含空格或为null。 System.out.println("Is one empty? " + StringUtils.isBlank(one)); System.out.println("Is two empty? " + StringUtils.isBlank(two)); System.out.println("Is three empty? " + StringUtils.isBlank(three)); System.out.println("Is four empty? " + StringUtils.isBlank(four)); System.out.println("Is five empty? " + StringUtils.isBlank(five)); //另一方面,StringUtils.isNotBlank()方法补充了 //前一种方法。它将检查被测试的字符串是否为空。 System.out.println("Is one not empty? " + StringUtils.isNotBlank(one)); System.out.println("Is two not empty? " + StringUtils.isNotBlank(two)); System.out.println("Is three not empty? " + StringUtils.isNotBlank(three)); System.out.println("Is four not empty? " + StringUtils.isNotBlank(four)); System.out.println("Is five not empty? " + StringUtils.isNotBlank(five)); } }
结果如下:
Is one empty? true Is two empty? true Is three empty? true Is four empty? true Is five empty? false Is one not empty? false Is two not empty? false Is three not empty? false Is four not empty? false Is five not empty? true
Maven依赖
<!-- https://search.maven.org/remotecontent?filepath=org/apache/commons/commons-lang3/3.9/commons-lang3-3.9.jar --> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.9</version> </dependency>