是否有可能在多個字符之後將Java字符串截斷爲最接近的單詞邊界。類似於PHP的wordwrap()函數,如example所示。在最近的單詞邊界上截斷字符串
8
A
回答
14
使用java.text.BreakIterator
,是這樣的:
String s = ...;
int number_chars = ...;
BreakIterator bi = BreakIterator.getWordInstance();
bi.setText(s);
int first_after = bi.following(number_chars);
// to truncate:
s = s.substring(0, first_after);
4
您可以使用正則表達式
Matcher m = Pattern.compile("^.{0,10}\\b").matches(str);
m.find();
String first10char = m.group(0);
2
用第一種方法,你會最終有一個長度大於number_chars更大。如果你需要一個確切的最大值或更小的值,比如Twitter消息,請參見下面的我的實現。
請注意,正則表達式方法使用空格來分隔單詞,而BreakIterator即使分詞含有逗號和其他字符也會分解單詞。這是更可取的。
這裏是我的全部功能:
與BreakIterator
/**
* Truncate text to the nearest word, up to a maximum length specified.
*
* @param text
* @param maxLength
* @return
*/
private String truncateText(String text, int maxLength) {
if(text != null && text.length() > maxLength) {
BreakIterator bi = BreakIterator.getWordInstance();
bi.setText(text);
if(bi.isBoundary(maxLength-1)) {
return text.substring(0, maxLength-2);
} else {
int preceding = bi.preceding(maxLength-1);
return text.substring(0, preceding-1);
}
} else {
return text;
}
}
0
解決方案是不是真的簡單,當破句是URL,它打破URL不是很好的方式。我寧願使用我的解決方案:
public static String truncateText(String text, int maxLength) {
if (text != null && text.length() < maxLength) {
return text;
}
List<String> words = Splitter.on(" ").splitToList(text);
List<String> truncated = new ArrayList<>();
int totalCount = 0;
for (String word : words) {
int wordLength = word.length();
if (totalCount + 1 + wordLength > maxLength) { // +1 because of space
break;
}
totalCount += 1; // space
totalCount += wordLength;
truncated.add(word);
}
String truncResult = Joiner.on(" ").join(truncated);
return truncResult + " ...";
}
分流器/連接器來自番石榴。我還在我的使用cas中添加了...
(可以省略)。
相關問題
- 1. PHP:在單詞邊界截斷文本
- 2. 在.NET C中的整個單詞上截斷字符串#
- 3. 在可能的英文單詞邊界上分割字符串
- 4. Div正在截斷單詞和包裝的邊界
- 5. Python:在單詞邊界上拆分unicode字符串
- 6. 如何使用省略號自動截斷單詞邊界上的UILabel?
- 7. 截斷字符串
- 8. 截斷在python字符串
- 9. 邊界字符串
- 10. 字符串截斷的ClientDataSet
- 11. RODBC字符串被截斷
- 12. UILabel字符串截斷
- 13. BufferedWriter將截斷字符串
- 14. PHP截斷字符串
- 15. Python截斷長字符串
- 16. KRL:截斷字符串
- 17. x個字符後截斷字符串
- 18. PHP在字符串中結合兩個最接近的詞
- 19. 邊界上的分詞
- 20. 截斷字符串在Div元素
- 21. 在mvc homecontroller中截斷字符串javascript
- 22. 合併兩個正則表達式來截斷字符串裏的單詞
- 23. 如果包含長於特定值的單詞,則截斷一個字符串
- 24. 在iPhone上的Core-Data中截斷的字符串
- 25. RegEx帶特殊字符的單詞邊界
- 26. 按字節截斷字符串
- 27. android spinners中的截斷字符串
- 28. 使用的sscanf()截斷字符串
- 29. 截斷沒有空白的字符串
- 30. 的JavaScript字符串截斷逗號
這是非常感謝,雖然會aa bi.truncateAt()已經太多要求? :) – 2009-02-05 06:02:34