Skip to content

Instantly share code, notes, and snippets.

@guangtuan
Created September 30, 2020 08:28
Show Gist options
  • Save guangtuan/cf64ebb686b4930810a505bf4740c5e3 to your computer and use it in GitHub Desktop.
Save guangtuan/cf64ebb686b4930810a505bf4740c5e3 to your computer and use it in GitHub Desktop.
TextStoreUtil
package cn.agilean.valuekanban.shared;
import org.springframework.stereotype.Component;
import java.nio.charset.StandardCharsets;
public class TextStoreUtil {
private int defaultMaxByteCountOfText = 500;
public String getMaxStorableSubString(String source) {
return getMaxStorableSubString(source, this.defaultMaxByteCountOfText);
}
public String getMaxStorableSubString(String source, int maxByteCount) {
if (getByteCount(source) <= maxByteCount) {
return source;
}
int cutIndex = getCutIndex(source, maxByteCount);
if (cutIndex == -1) {
// 全部按照汉字计算
return source.substring(0, maxByteCount / 3);
}
return source.substring(0, cutIndex);
}
private static int getCutIndex(final String source, final int maxByteCount) {
final int sourceLength = source.length();
int cutIndex = sourceLength / 2;
int lastOutOfBoundIndex = sourceLength;
int maxRetry = sourceLength / 3;
int retryCount = 0;
while (true) {
int byteCount = getByteCount(source.substring(0, cutIndex));
if (byteCount > maxByteCount) {
// 当前截取的字符串的字节数超出限制
lastOutOfBoundIndex = cutIndex;
cutIndex = cutIndex / 2;
} else if (maxByteCount - byteCount > 3) {
// 当前截取的字符串的字节数和限制差3个以内认为是可以了(实际这里最糟糕的情况下会少两个字母,数字)
cutIndex = (cutIndex + lastOutOfBoundIndex) / 2;
} else {
return cutIndex;
}
retryCount++;
if (retryCount > maxRetry) {
return -1;
}
}
}
private static int getByteCount(String str) {
return str.getBytes(StandardCharsets.UTF_8).length;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment