public class MyTest1 {
@Test
public void test() {
String s = "112我似そして懂12非懂2";
s = "てそしてててててそしてててて";
try {
System.out.println(substring(s,10));
System.out.println(substring(s,7));
System.out.println(substring(s,5));
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 支持 GBK UTF-8 截取
* @param orignal
* @param count
* @return
* @throws UnsupportedEncodingException
*/
public static String substring(String orignal, int count)
throws UnsupportedEncodingException {
if (orignal != null && !"".equals(orignal)) {
if (count > 0 && count < orignal.getBytes().length) {
StringBuffer buff = new StringBuffer();
char c;
for (int i = 0; i < count; i++) {
c = orignal.charAt(i);
buff.append(c);
count-=(charLength(c)-1);
}
return buff.toString();
}
}
return orignal;
}
public static int charLength(char c){
return String.valueOf(c).getBytes().length;
}
}
Java 按字节截取字符串
最新推荐文章于 2024-07-30 03:18:59 发布