要判讀String是否為空字符串,比較簡單,只要判斷該String的length是否為0就可以,或者直接用方法isEmpty()來判斷。
但很多時候我們也會把由一些不可見的字符組成的String也當(dāng)成是空字符串(e.g, space, tab, etc),這時候就不能單用length或isEmpty()來判斷了,因為technically上來說,這個String是非空的。這時候可以用String的方法trim(),去掉前導(dǎo)空白和后導(dǎo)空白,再判斷是否為空。
例如:
1
public class TestEmpty
2
{
3
public static void main(String[] args){
4
String a = " ";
5
6
// if (a.isEmpty())
7
if (a.trim().isEmpty())
8
{
9
System.out.println("It is empty");
10
}
11
else
12
{
13
System.out.println("It is not empty");
14
}
15
}
16
}
17
18

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

結(jié)果當(dāng)然是:It is empty
PS:Java Doc
public String trim()
Returns a copy of the string, with leading and trailing whitespace omitted.