Truncating Strings by Bytes

后端 未结 13 1736
醉酒成梦
醉酒成梦 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条回答
  •  旧巷少年郎
    2021-02-06 04:37

    you could convert the string to bytes and convert just those bytes back to a string.

    public static String substring(String text, int maxBytes) {
       StringBuilder ret = new StringBuilder();
       for(int i = 0;i < text.length(); i++) {
           // works out how many bytes a character takes, 
           // and removes these from the total allowed.
           if((maxBytes -= text.substring(i, i+1).getBytes().length) < 0) break;
           ret.append(text.charAt(i));
       }
       return ret.toString();
    }
    

提交回复
热议问题