String.isBlank()
– 在 Java 中检查空白或空字符串
学会使用String.isBlank()
方法确定给定的字符串是空白还是空,或者仅包含空格。isBlank()
方法已添加到 Java 11 中。
要检查给定的字符串是否没有偶数空格,请使用String.isEmpty()
方法。
1. String.isBlank()
方法
如果给定的字符串为空或仅包含空格代码点,则此方法返回true
,否则返回false
。
它使用Character.isWhitespace(char)
方法确定空白字符。
/**
* returns - true if the string is empty or contains only white space codepoints
* - otherwise false
*/
public boolean isBlank()
2. String.isBlank()
示例
检查给定字符串是否为空的 Java 程序。
public class Main
{
public static void main(String[] args)
{
System.out.println( "ABC".isBlank() ); //false
System.out.println( " ABC ".isBlank() ); //false
System.out.println( " ".isBlank() ); //true
System.out.println( "".isBlank() ); //true
}
}
程序输出。
false
false
true
true
3. isBlank()
与isEmpty()
两种方法都用于检查 Java 中的空白或空字符串。 两种方法之间的区别在于,当且仅当字符串长度为 0 时,isEmpty()
方法返回true
。
isBlank()
方法仅检查非空白字符。 它不检查字符串长度。
public class Main
{
public static void main(String[] args)
{
System.out.println( "ABC".isBlank() ); //false
System.out.println( " ".isBlank() ); //true
System.out.println( "ABC".isEmpty() ); //false
System.out.println( " ".isEmpty() ); //false
}
}
程序输出:
false
true
false
false
学习愉快!