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

来源:互联网 发布:韦德的数据 编辑:程序博客网 时间:2024/04/27 22:20

以下分别是两种实现方式:

第一种:

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