[code]public class A {
public static void main(String args[]) {
System.out.println(subString("sdf23我12", 7));
}
private static String subString(String string, int length) {
String result = null;
byte[] bytes = string.getBytes(); // 获取字节数组
int index = bytes.length < length ? bytes.length : length; // 如果要截取的字符串大于原来长度则全部截取
while (true) {
result = string.substring(0, index--); //根据上面定义的长度尝试截取
if (result.getBytes().length <= length) //判断截取后的字节长度是否满足要求
break;
}
return result;
}
}[/code] |