public static String subStr(String str, int subSLength) { String subStr =""; try { if (str == null) return ""; else{ int tempSubLength = subSLength;//截取字节数 subStr = str.substring(0, str.length()<subSLength ? str.length() : subSLength);//截取的子串 int subStrByetsL = subStr.getBytes("GBK").length;//截取子串的字节长度 // 说明截取的字符串中包含有汉字 while (subStrByetsL > tempSubLength){ int subSLengthTemp = --subSLength; subStr = str.substring(0, subSLengthTemp>str.length() ? str.length() : subSLengthTemp); subStrByetsL = subStr.getBytes("GBK").length; } } } catch (Exception e) { System.out.println(e.getMessage()); } return subStr; }
public static void main(String[] args) { String name = "踩踩踩12411测114测"; System.out.println("字符串长度"+name.length()); System.out.println("截取字符串前10个字节的结果"+subStr(name,10)); }
结果:
原字符串值:踩踩踩12411测114测 字符串长度:13 截取字符串前10个字节的结果:踩踩踩1241