2009-02-05 8 views

Répondre

14

Utilisez un java.text.BreakIterator, quelque chose comme ceci:

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

C'est très bien, même si un bi.truncateAt() aurait été trop demander? :) –

+0

Assurez-vous de tester que number_chars n'est pas plus grand que s.length(), sinon vous obtenez une exception. Pour info, j'ai essayé d'éditer le Java pour refléter ce fait, mais le montage a été rejeté. – mooreds

4

Vous pouvez utiliser une expression régulière

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

Avec la première approche vous finira avec une plus grande longueur que number_chars. Si vous avez besoin d'un maximum exact ou moins, comme pour un message Twitter, voir ma mise en œuvre ci-dessous.

Notez que l'approche regexp utilise un espace pour délimiter les mots, tandis que BreakIterator casse les mots même s'ils ont des virgules et d'autres caractères. Ceci est plus souhaitable.

Voici ma pleine fonction:

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

Solution avec BreakIterator est pas vraiment simple lorsque la peine est la rupture URL, il se casse URL pas très belle façon. J'ai plutôt utilisé la solution de mine:

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

Le séparateur/jointure vient de goyave. J'ajoute également ... à la fin dans mon cas d'utilisation (peut être ommited).

Questions connexes