string的length()方法返回字符串中unicode字符的数量,而getbytes().length返回特定编码下的字节数;2. 处理ascii字符时两者结果相同,但对中文等非ascii字符,因编码不同(如utf-8中一个中文占3字节,gbk中占2字节),字节数通常大于字符数;3. 应根据需求选择:若需字符个数(如字符串截取、遍历)使用length(),若涉及存储或传输中字节限制则使用getbytes().length;4. 为避免null调用length()抛出nullpointerexception,应进行判空检查,可通过if判断、三元运算符、objects.requirenonnullelse(java 9+)、optional(java 8+)或apache commons lang的stringutils.length()实现安全获取长度。

String的length()方法是Java中获取字符串长度最直接的方式。它返回的是字符串中字符的数量,是一个整数值。
解决方案
在Java中,获取字符串长度非常简单,只需调用String对象的length()方法即可。下面是一些示例和注意事项:
立即学习“Java免费学习笔记(深入)”;
public class StringLengthExample {
public static void main(String[] args) {
String str1 = "Hello World";
int length1 = str1.length();
System.out.println("Length of '" + str1 + "': " + length1); // 输出:11
String str2 = "";
int length2 = str2.length();
System.out.println("Length of empty string: " + length2); // 输出:0
String str3 = "你好世界"; // 包含中文
int length3 = str3.length();
System.out.println("Length of '" + str3 + "': " + length3); // 输出:4,注意这里是字符数,不是字节数
String str4 = null;
// int length4 = str4.length(); // 这里会抛出NullPointerException,需要避免
if (str4 != null) {
int length4 = str4.length();
System.out.println("Length of '" + str4 + "': " + length4);
} else {
System.out.println("String is null, cannot get length.");
}
}
}需要注意的是,
length()方法返回的是Unicode字符的数量,而不是字节数。对于包含中文或其他非ASCII字符的字符串,一个字符占用多个字节,但
length()仍然返回字符的个数。
另外,对
null字符串调用
length()方法会抛出
NullPointerException,因此在使用前务必进行判空检查。
String的length()方法和getBytes().length的区别?
length()方法返回的是字符串中字符的数量(Unicode码点数量),而
getBytes().length返回的是字符串在特定编码下的字节数。这两者在处理非ASCII字符时有显著差异。
public class StringByteLengthExample {
public static void main(String[] args) {
String str = "你好abc";
int charLength = str.length();
System.out.println("Character length: " + charLength); // 输出:5
int byteLengthUTF8 = str.getBytes("UTF-8").length;
System.out.println("Byte length in UTF-8: " + byteLengthUTF8); // 输出:9 (每个中文占3个字节)
int byteLengthGBK = str.getBytes("GBK").length;
System.out.println("Byte length in GBK: " + byteLengthGBK); // 输出:7 (每个中文占2个字节)
String strAscii = "abc";
int asciiCharLength = strAscii.length();
System.out.println("Character length (ASCII): " + asciiCharLength); // 输出:3
int asciiByteLengthUTF8 = strAscii.getBytes("UTF-8").length;
System.out.println("Byte length in UTF-8 (ASCII): " + asciiByteLengthUTF8); // 输出:3
}
}可以看到,对于纯ASCII字符串,
length()和
getBytes("UTF-8").length 的结果是一样的。但对于包含中文的字符串,由于中文在UTF-8编码中通常占用3个字节,在GBK编码中通常占用2个字节,所以字节数会大于字符数。
什么时候应该用length(),什么时候应该用getBytes().length?
-
使用
length()
的场景:- 需要知道字符串包含多少个字符。
- 进行字符串截取、循环遍历等操作,需要基于字符数量进行。
- 不需要关心字符串的底层存储方式和编码。
-
使用
getBytes().length
的场景:- 需要知道字符串在特定编码下占用的字节数,例如在网络传输、文件存储等场景。
- 需要限制字符串的字节数,例如数据库字段的长度限制。
- 需要进行精确的字节级别的操作。
举个例子,如果需要限制用户输入的字符串长度不超过10个字符,应该使用
length()。 如果需要限制用户输入的字符串在UTF-8编码下不超过20个字节,应该使用
getBytes("UTF-8").length。
如何避免String为null时调用length()方法报错?
处理
null字符串是Java编程中常见的任务。直接对
null字符串调用
length()方法会导致
NullPointerException。以下是一些避免这种情况的方法:
-
判空检查:
这是最常见和最直接的方法。在使用
length()
之前,先判断字符串是否为null
。String str = null; if (str != null) { int length = str.length(); System.out.println("Length: " + length); } else { System.out.println("String is null."); } -
使用三元运算符:
可以使用三元运算符简化判空检查。
String str = null; int length = (str != null) ? str.length() : 0; System.out.println("Length: " + length); // 输出 0 -
使用
Objects.requireNonNullElse
(Java 9+):Java 9 引入了
Objects.requireNonNullElse
方法,可以提供一个默认值来代替null
。import java.util.Objects; public class NullSafeLength { public static void main(String[] args) { String str = null; String safeStr = Objects.requireNonNullElse(str, ""); int length = safeStr.length(); System.out.println("Length: " + length); // 输出 0 } } -
使用Optional (Java 8+):
Optional
类可以用来包装可能为null
的值,并提供一系列方法来处理null
值。import java.util.Optional; public class NullSafeLengthOptional { public static void main(String[] args) { String str = null; int length = Optional.ofNullable(str).orElse("").length(); System.out.println("Length: " + length); // 输出 0 } } -
使用StringUtils (Apache Commons Lang):
Apache Commons Lang 库提供了一个
StringUtils
类,其中包含许多实用的字符串处理方法,包括length()
的空安全版本。import org.apache.commons.lang3.StringUtils; public class NullSafeLengthStringUtils { public static void main(String[] args) { String str = null; int length = StringUtils.length(str); System.out.println("Length: " + length); // 输出 0 } }
选择哪种方法取决于具体的场景和个人偏好。判空检查是最基本的方法,适用于所有Java版本。
Objects.requireNonNullElse和
Optional是Java 8+ 引入的,可以使代码更简洁。
StringUtils提供了更多的字符串处理功能,如果项目中已经使用了 Apache Commons Lang 库,那么使用
StringUtils.length()是一个不错的选择。











