Truncating Strings by Bytes

后端 未结 13 1739
醉酒成梦
醉酒成梦 2021-02-06 04:21

I create the following for truncating a string in java to a new string with a given number of bytes.

        String truncatedValue = \"\";
        String curren         


        
13条回答
  •  旧时难觅i
    2021-02-06 04:42

    This one could not be the more efficient solution but works

    public static String substring(String s, int byteLimit) {
        if (s.getBytes().length <= byteLimit) {
            return s;
        }
    
        int n = Math.min(byteLimit-1, s.length()-1);
        do {
            s = s.substring(0, n--);
        } while (s.getBytes().length > byteLimit);
    
        return s;
    }
    

提交回复
热议问题