我创建了以下代码用于在Java中将字符串截断为给定字节数的新字符串。
String truncatedValue = "";
String currentValue = string;
int pivotIndex = (int) Math.round(((double) string.length())/2);
while(!truncatedValue.equals(currentValue)){
currentValue = string.substring(0,pivotIndex);
byte[] bytes = null;
bytes = currentValue.getBytes(encoding);
if(bytes==null){
return string;
}
int byteLength = bytes.length;
int newIndex = (int) Math.round(((double) pivotIndex)/2);
if(byteLength > maxBytesLength){
pivotIndex = newIndex;
} else if(byteLength < maxBytesLength){
pivotIndex = pivotIndex + 1;
} else {
truncatedValue = currentValue;
}
}
return truncatedValue;
这是我想到的第一件事,我知道我可以改进它。我看到另一篇帖子在问类似的问题,但他们是使用字节来截取字符串而不是使用String.substring
。我认为在我的情况下我更愿意使用String.substring
。
编辑:我刚刚删除了UTF8的参考,因为我也想能够适用于不同的存储类型。