Truncating Strings by Bytes

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

    The more sane solution is using decoder:

    final Charset CHARSET = Charset.forName("UTF-8"); // or any other charset
    final byte[] bytes = inputString.getBytes(CHARSET);
    final CharsetDecoder decoder = CHARSET.newDecoder();
    decoder.onMalformedInput(CodingErrorAction.IGNORE);
    decoder.reset();
    final CharBuffer decoded = decoder.decode(ByteBuffer.wrap(bytes, 0, limit));
    final String outputString = decoded.toString();
    
    0 讨论(0)
提交回复
热议问题