如果長度超過10個字符,我想修剪一個字符串。根據字符串長度修整字符串
假設如果字符串長度爲12(String s="abcdafghijkl"
),那麼新修剪的字符串將包含"abcdefgh.."
。
我該如何做到這一點?
如果長度超過10個字符,我想修剪一個字符串。根據字符串長度修整字符串
假設如果字符串長度爲12(String s="abcdafghijkl"
),那麼新修剪的字符串將包含"abcdefgh.."
。
我該如何做到這一點?
s = s.substring(0, Math.min(s.length(), 10));
使用Math.min
這樣避免了在字符串已經比10
短的情況下例外。
注:
上述聲明真實微調。如果實際上想要用截點替換最後三個(!)字符,則使用Apache Commons StringUtils.abbreviate
。
這可能表現不正確如果您的字符串包含BMP以外的Unicode代碼點;例如表情符號。有關適用於所有Unicode代碼點的解決方案,請參閱@ sibnick的solution。
1 - 一個Unicode代碼點不是在平面0(BMP)被表示爲在一個String
「代理對」(即,兩個char
值)。通過忽略這一點,我們可以修剪到少於10個代碼點,或者(更糟糕的是)在代理對中間截斷。另一方面,String.length()
不再是衡量Unicode文本長度的一種理想方法,因此基於它的修改可能是錯誤的。
晚會有點晚,但如果使用apache commons StringUtils ,我更喜歡使用s = StringUtils.left(s,10),而不是試圖理清java的substring()的設計者試圖傳達的東西。這也避免了拋出異常執行一些簡單的事情,比如從不確定長度的字符串中提取前幾個字符,這是一種並不罕見的操作。 – 2012-12-12 15:27:30
@SteeveMcCauley - 爲了保護Java設計人員,儘管split的第二個參數是子字符串結尾後的字符pos,這稍微不直觀,但這樣做也可能更方便在更多情況下。此外,這是一位經驗豐富的Java程序員只記得的東西。 – 2013-07-05 06:03:29
@SteeveMcCauley - 這是一些*沒有經驗的* java程序員應該在javadocs中查找......而不是依靠直覺。 – 2015-07-15 23:10:39
s = s.length() > 10 ? s.substring(0, 9) : s;
StringUtils.abbreviate
從Apache Commons Lang庫可能是您的朋友:
StringUtils.abbreviate("abcdefg", 6) = "abc..."
StringUtils.abbreviate("abcdefg", 7) = "abcdefg"
StringUtils.abbreviate("abcdefg", 8) = "abcdefg"
StringUtils.abbreviate("abcdefg", 4) = "a..."
或者你也可以使用此方法的情況下,你沒有手StringUtils的:
public static String abbreviateString(String input, int maxLength) {
if (input.length() <= maxLength)
return input;
else
return input.substring(0, maxLength-2) + "..";
}
像往常一樣,沒有人關心UTF-16代理對。看到他們:org.apache.commons /公地lang3的What are the most common non-BMP Unicode characters in actual use?即使作者
你可以看到這個樣本中正確的代碼和常規代碼之間的區別:
public static void main(String[] args) {
//string with FACE WITH TEARS OF JOY symbol
String s = "abcdafghi\uD83D\uDE02cdefg";
int maxWidth = 10;
System.out.println(s);
//do not care about UTF-16 surrogate pairs
System.out.println(s.substring(0, Math.min(s.length(), maxWidth)));
//correctly process UTF-16 surrogate pairs
if(s.length()>maxWidth){
int correctedMaxWidth = (Character.isLowSurrogate(s.charAt(maxWidth)))&&maxWidth>0 ? maxWidth-1 : maxWidth;
System.out.println(s.substring(0, Math.min(s.length(), correctedMaxWidth)));
}
}
有一個StringUtils
功能,做到這一點。
s = StringUtils.left(s, 10)
如果len個字符不可用,或者字符串爲null,該字符串將沒有例外返回。如果len爲負值,則返回空字符串。
StringUtils.left(null,)= null
StringUtils。左(,-ve)= 「」
StringUtils.left( 「」,*)= 「」
StringUtils.left( 「ABC」,0)= 「」
StringUtils.left( 「ABC」,2 )= 「AB」
StringUtils.left( 「ABC」,4)= 「ABC」
禮貌:吊杆麥考利
萬一你正在尋找一種方式來修剪並保留一個字符串的最後10個字符。
s = s.substring(Math.max(s.length(),10)-10);
可能重複的[最多N個字符](http://stackoverflow.com/questions/1583940/up-to-first-n-characters) – 2011-12-14 05:14:50