您的位置:首页 > 编程语言 > Java开发

Java 按字节截取字符串

2017-03-27 11:40 176 查看
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;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: