In Java, String needs to be truncated by the number of bytes if it is an API linkage with a byte limit. In Japanese, Charaset is used for 2 bytes, 3 bytes, and so on. I thought about it for a moment, so I wrote the code as a memorandum I haven't moved it, but maybe it's okay ...
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;
}
Recommended Posts