package com.chinatricon.spring;
public class 截取指定的字符长度 {
public String subString(String str, int subBytes) {
int bytes = 0; // 用来存储字符串的总字节数
for (int i = 0; i < str.length(); i++) {
if (bytes == subBytes) {
return str.substring(0, i);
}
char c = str.charAt(i);
if (c < 256) {
bytes += 1; // 英文字符的字节数看作1
} else {
bytes += 2; // 中文字符的字节数看作2
if (bytes - subBytes == 1) {
return str.substring(0, i);
}
}
}
return str;
}
public static void main(String[] args) {
截取指定的字符长度 sb = new 截取指定的字符长度();
System.out.println(sb.subString("ABC坏蛋",6));
}
}