下面是我用來修剪我的webapps中的長字符串的方法。 「軟」boolean
正如你所說,如果設置爲true
將保留最後一個字。 這是最簡潔的做法,我可以想出使用StringBuffer,比重新創建一個不可變的字符串更有效。
public static String trimString(String string, int length, boolean soft) {
if(string == null || string.trim().isEmpty()){
return string;
}
StringBuffer sb = new StringBuffer(string);
int actualLength = length - 3;
if(sb.length() > actualLength){
// -3 because we add 3 dots at the end. Returned string length has to be length including the dots.
if(!soft)
return escapeHtml(sb.insert(actualLength, "...").substring(0, actualLength+3));
else {
int endIndex = sb.indexOf(" ",actualLength);
return escapeHtml(sb.insert(endIndex,"...").substring(0, endIndex+3));
}
}
return string;
}
更新
我已經改變了代碼,以便在...
StringBuffer的追加,這是爲了防止不必要的String
創作含蓄緩慢且浪費。
注:escapeHtml
是來自Apache的公共靜態導入:
import static org.apache.commons.lang.StringEscapeUtils.escapeHtml;
你可以刪除它,代碼應該工作一樣。
來源
2011-10-12 09:50:42
Ali
如何'StringBuffer'幫助這裏的表現?沒有任何理由說明爲什麼'StringBuffer'上的'substring','indexOf'和'length'會比'String'快。 –
讓我澄清一下,提問者說,這是標記,然後把繩子放在一起。每次他在字符串上追加新的令牌時,整個字符串都會被銷燬並重新創建。對於長字符串,這個操作比使用'StringBuffer'要昂貴得多。雖然我同意,考慮到StringBuffer被創建,並且當我們返回時,我們有效地創建了一個字符串至少3次(substring,append dots,escape [,trim]),性能差異可能忽略不計。 – Ali
問題是,在你的代碼中,你不會追加任何東西到'StringBuffer'。 –