我創建以下代碼以將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的參考,因爲我寧願能夠爲不同的存儲類型做到這一點。
我會修改你的問題。您正試圖將字符串放入不能超過maxUTF8BytesLength的字節數組中。你想使用UTF-8編碼。你想複製儘可能多的字符。正確? – gawi 2010-08-26 15:51:01
對,我會說這是正確的。我也想有效地做到這一點。 – stevebot 2010-08-26 16:04:02
我剛剛編輯的問題不參考UTF-8。對不起,這是誤導。 – stevebot 2010-08-26 16:09:33