java 字符串按大小(占字节数)切分

工作中可能会遇到字符串按照占字节数大小进行切分的需求,写了一个方法,用于实现这个功能

public static List<String> splitBySize(String value, int length) {
        char[] cs = value.toCharArray();
        StringBuilder result = new StringBuilder();
        List<String> resultList = new ArrayList<String>();
        int index = 0;
        for (char c: cs){
            index += String.valueOf(c).getBytes().length;
            if (index > length){
                resultList.add(result.toString());
                result.delete(0,index-1);
                index = 0;
            }else {
                result.append(c);
            }
        }
        
        return resultList;
    }

感谢上善若水的帮助,原代码有遗漏字符的bug,更新代码如下:

public static List<String> splitBySize(String value, int length) {
        char[] cs = value.toCharArray();
        StringBuilder result = new StringBuilder();
        List<String> resultList = new ArrayList<String>();
        int index = 0;
        for (char c: cs){
            index += String.valueOf(c).getBytes().length;
            if (index > length){
                resultList.add(result.toString());
                result.delete(0,index-1);
                index = 0;
            }else {
                result.append(c);
            }
        }
        if(result.length()>0){
            resultList.add(result.toString());
        }
        return resultList;
    }
经验分享 程序员 微信小程序 职场和发展