10

Is it possible to truncate a Java string to the closest word boundary after a number of characters. Similar to the PHP wordwrap() function, shown in this example.

4 Answers 4

14

Use a java.text.BreakIterator, something like this:

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);
2
  • This is great thanks, although would aa bi.truncateAt() have been too much to ask for? :)
    – Xenph Yan
    Feb 5, 2009 at 6:02
  • 1
    Make sure you test that number_chars is not larger than s.length(), otherwise you get an exception. FYI, I tried to edit the java to reflect this fact, but the edit was rejected.
    – mooreds
    Nov 7, 2011 at 5:43
4

You can use regular expression

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

With the first approach you will end up with a length bigger than number_chars. If you need an exact maximum or less, like for a Twitter message, see my implementation below.

Note that the regexp approach uses a space to delimit the words, while BreakIterator breaks up words even if they have commas and other characters. This is more desirable.

Here is my full function:

/**
     * 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 with BreakIterator is not really straightforward when breaking sentence is URL, it breaks URL not very nice way. I rather used mine solution:

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 is from guava. I am also adding ... at the end in my use cas (can be ommited).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.