以下分别是两种实现方式:
第一种:
public static String getStr(String str,int index){
if(str==null || str.length()==0 || index==0){
return "";
}
int count=0;
StringBuffer sb = new StringBuffer("");
for (int i = 0; i < str.length(); i++) {
String s = String.valueOf(str.charAt(i));
if(s.getBytes().length==2){
count+=2;
}else{
count+=1;
}
if(count<=index){
sb.append(s);
}
}
return sb.toString();
}
第二种:
public static String getStr2(String str,int index){
if(str==null || str.length()==0 || index==0){
return "";
}
int count=0;
StringBuffer sb = new StringBuffer("");
for (int i = 0; i < str.length(); i++) {
char c= str.charAt(i);
if(c>255){
count+=2;
}else{
count+=1;
}
if(count<=index){
sb.append(c);
}
}
return sb.toString();
}