Java String length()
length() 方法用來取得字串的長度(字元數)。
語法
string.length()
回傳字串中的字元數量。
範例
String s = "Hello";
int len = s.length();
System.out.println(len); // 5
String chinese = "你好世界";
System.out.println(chinese.length()); // 4
String empty = "";
System.out.println(empty.length()); // 0
實際應用
檢查字串長度
String password = "abc123";
if (password.length() < 8) {
System.out.println("密碼長度不足 8 位");
}
遍歷字串
String s = "Hello";
for (int i = 0; i < s.length(); i++) {
System.out.println(s.charAt(i));
}
isEmpty() 和 isBlank()
除了 length() 外,還有其他方法可以檢查字串:
String s1 = "";
String s2 = " ";
String s3 = "Hello";
// isEmpty() - 檢查長度是否為 0
System.out.println(s1.isEmpty()); // true
System.out.println(s2.isEmpty()); // false(有空白字元)
System.out.println(s3.isEmpty()); // false
// isBlank() - 檢查是否為空白字串(Java 11+)
System.out.println(s1.isBlank()); // true
System.out.println(s2.isBlank()); // true(只有空白)
System.out.println(s3.isBlank()); // false
注意事項
length() 回傳的是字元數,不是位元組數:
String s = "你好";
System.out.println(s.length()); // 2(字元數)
System.out.println(s.getBytes().length); // 6(UTF-8 位元組數)