java汉字如何截取
截取汉字的常见方法
在Java中截取汉字需要特别注意汉字的多字节特性。由于汉字在UTF-8编码下通常占用3个字节,直接使用String.substring()可能导致截取到不完整的字符。
使用String.codePointCount()和String.offsetByCodePoints()
String text = "这是一个测试字符串";
int start = 2; // 起始位置(从0开始)
int end = 5; // 结束位置
int realStart = text.offsetByCodePoints(0, start);
int realEnd = text.offsetByCodePoints(0, end);
String result = text.substring(realStart, realEnd);
System.out.println(result); // 输出"一个测"
转换为字符数组处理
String text = "汉字截取示例";
char[] chars = text.toCharArray();
int start = 1;
int length = 3;
StringBuilder sb = new StringBuilder();
for(int i=start; i<start+length && i<chars.length; i++){
sb.append(chars[i]);
}
System.out.println(sb.toString()); // 输出"字截取"
使用Apache Commons Lang库
如果项目允许使用第三方库,StringUtils提供更简便的方法:
import org.apache.commons.lang3.StringUtils;
String text = "处理汉字截取";
String result = StringUtils.substring(text, 2, 5);
System.out.println(result); // 输出"汉字截"
处理混合字符串的情况
当字符串包含汉字和其他字符时,需要更谨慎的处理:

String mixed = "abc汉字123";
int byteLength = 5; // 要截取的字节长度
int charCount = 0;
int byteCount = 0;
while(charCount < mixed.length() && byteCount < byteLength){
char c = mixed.charAt(charCount);
byteCount += (c < 128) ? 1 : 3; // ASCII字符1字节,汉字3字节
if(byteCount <= byteLength){
charCount++;
}
}
String result = mixed.substring(0, charCount);
System.out.println(result); // 输出"abc汉"
注意事项
- 不同编码下汉字占用的字节数可能不同(GBK编码中汉字占2个字节)
- 考虑字符串边界情况,避免
StringIndexOutOfBoundsException - 对于包含emoji等特殊字符的情况,建议使用
codePoint相关方法处理






