java代码
/**
* str字符串,count要截取的字节长度
*/
public static String getLength(String str,int count){
if(null == str || str.length() == 0){
return "";
}
byte[] uri_bytes = str.getBytes();
//用来存储中文字节下标
List<Integer> list = new ArrayList<>();
for(int i=0; i<count; i++){
// 判断中文,utf-8中一个中文3个字节,当中每个字节的ASCII值<0
if(Integer.valueOf(String.valueOf(uri_bytes[i]))<0){
if(list.size() == 3){
list.clear();
list.add(i);
}else{
list.add(i);
}
}
}
if(list.size() != 3 && list.size() != 0){
byte[] new_uri_value=new byte[count-list.size()];
System.arraycopy(uri_bytes, 0, new_uri_value, 0, count-list.size());
return new String(new_uri_value);
}else{
byte[] new_uri_value=new byte[count];
System.arraycopy(uri_bytes, 0, new_uri_value, 0, count);
return new String(new_uri_value);
}
}