LoginSignup
1
2

More than 3 years have passed since last update.

Java String バイト文字列切り捨て 文字化け対応

Last updated at Posted at 2017-05-11

Java で String をバイト数制限があるAPI連携だとバイト数で切り捨てる必要がある
日本語は Charaset で 2バイト, 3バイト... と文字の途中で切り捨てると文字変になりそう
ちょっと考えたので備忘録としてコード記載
動かしてないけどたぶん大丈夫かと...

Sample.java
public static String truncateByte(String s, int length, Charset charset) {
    if (StringUtils.isEmpty(s) || length <= 0) {
        return s == null ? null : "";
    }
    if (s.getBytes(charset).length <= length) {
        return s;
    }
    String r = new String(s.getBytes(charset), 0, length, charset);
    while (r.length() >= 0 && !s.startsWith(r)) {
        r = r.substring(0, r.length() - 1);
    }
    return r;
}
  1. 最初に空になるパターンはじく
  2. バイト数以内はそのまま
  3. バイト数切り捨てた文字を取得
  4. 元の文字が切り捨てた文字で始まるまで切り捨て文字を1文字ずつ切っていく
  5. 切った文字を返す
1
2
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2