Как обрезать строку байтами? - PullRequest
0 голосов
/ 09 апреля 2019

У меня есть текст UTF-8, и я хочу обрезать / урезать его байтами, чтобы получить новая строка в костюмированной длине байтов.

public static String trimByBytes(String text, int longitudBytes) throws Exception {

    byte bytes_text[] = text.getBytes("UTF-8");
    int negativeBytes = 0;

    byte byte_trimmed[] = new byte[longitudBytes];
    if (byte_trimmed.length <= bytes_text.length) {
          //copy  array manually and count negativeBytes
        for (int i = 0; i < byte_trimmed.length; i++) {
            byte_trimmed[i] = bytes_text[i];
            if (byte_trimmed[i] < 0) {

                negativeBytes++;
            }
        }
         //if negativeBytes are odd
        if (negativeBytes % 2 != 0 && byte_trimmed[byte_trimmed.length - 1] < 0) {
            byte_trimmed[byte_trimmed.length - 1] = 0;//delete last

        }
    }else{
      for (int i = 0; i < bytes_text.length; i++) {
            byte_trimmed[i] = bytes_text[i];
        }

    }
    return new String(byte_trimmed);
}

}

например.

  • номенклатура: String trimByBytes (String str, int lengthOfBytes); trimByBytes (Gómez, 1)
  • Гомес имеет длину 6 байтов (но длина 5 символов)
  • Гомес урезан в 3 - это хорошо Го хорошо Гомес урезан в 2 - это G , но я хочу G (удалить нечетный символ)
  • Гомес, обрезанный в 1, это G хорошо Гомес, обрезанный в 8, это G Гомес

1 Ответ

0 голосов
/ 09 апреля 2019

Создайте явное CharsetDecoder и установите для него CodingErrorAction.IGNORE .

Поскольку CharsetDecoder работает с ByteBuffers, применение ограничения длины так же просто, как вызовметод байтового буфера limit :

String trimByBytes(String str, int lengthOfBytes) {
    byte[] bytes = str.getBytes(StandardCharsets.UTF_8);
    ByteBuffer buffer = ByteBuffer.wrap(bytes);

    if (lengthOfBytes < buffer.limit()) {
        buffer.limit(lengthOfBytes);
    }

    CharsetDecoder decoder = StandardCharsets.UTF_8.newDecoder();
    decoder.onMalformedInput(CodingErrorAction.IGNORE);

    try {
        return decoder.decode(buffer).toString();
    } catch (CharacterCodingException e) {
        // We will never get here.
        throw new RuntimeException(e);
    }
}
...