您的位置:首页 > 其它

截取带有中文字符串的字节索引

2009-08-08 03:11 281 查看
以下分别是两种实现方式:

第一种:

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();

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: