2009-02-05 49 views

回答

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); 
+0

這是非常感謝,雖然會aa bi.truncateAt()已經太多要求? :) – 2009-02-05 06:02:34

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中添加了...(可以省略)。