2009-02-05 15 views

risposta

14

Utilizzare un java.text.BreakIterator, qualcosa di simile:

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

Questo è fantastico, anche se un bi.truncateAt() sarebbe stato troppo chiedere? :) –

+0

Assicurati di verificare che number_chars non sia più grande di s.length(), altrimenti ottieni un'eccezione. Cordiali saluti, ho provato a modificare il java per riflettere questo fatto, ma la modifica è stata respinta. – mooreds

4

È possibile utilizzare le espressioni regolari

Matcher m = Pattern.compile("^.{0,10}\\b").matches(str); 
m.find(); 
String first10char = m.group(0); 
2

Con il primo approccio si finirà con una lunghezza più grande di number_chars. Se hai bisogno di un massimo esatto o meno, come per un messaggio di Twitter, vedi la mia implementazione qui sotto.

Si noti che l'approccio regexp utilizza uno spazio per delimitare le parole, mentre BreakIterator interrompe le parole anche se contengono virgole e altri caratteri. Questo è più desiderabile.

Qui è la mia funzione completa:

/** 
    * 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

Soluzione con BreakIterator non è davvero semplice quando si rompe frase è URL, si rompe URL non modo molto piacevole. Ho usato piuttosto la mia soluzione:

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 + " ..."; 
} 

Splitter/Joiner è di guava. Aggiungo anche ... alla fine nel mio uso cas (può essere omesso).

Problemi correlati