Truncating Strings by Bytes

后端 未结 13 1707
醉酒成梦
醉酒成梦 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:35

    This is my :

    private static final int FIELD_MAX = 2000;
    private static final Charset CHARSET =  Charset.forName("UTF-8"); 
    
    public String trancStatus(String status) {
    
        if (status != null && (status.getBytes(CHARSET).length > FIELD_MAX)) {
            int maxLength = FIELD_MAX;
    
            int left = 0, right = status.length();
            int index = 0, bytes = 0, sizeNextChar = 0;
    
            while (bytes != maxLength && (bytes > maxLength || (bytes + sizeNextChar < maxLength))) {
    
                index = left + (right - left) / 2;
    
                bytes = status.substring(0, index).getBytes(CHARSET).length;
                sizeNextChar = String.valueOf(status.charAt(index + 1)).getBytes(CHARSET).length;
    
                if (bytes < maxLength) {
                    left = index - 1;
                } else {
                    right = index + 1;
                }
            }
    
            return status.substring(0, index);
    
        } else {
            return status;
        }
    }
    

提交回复
热议问题