views:

971

answers:

2

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.

+6  A: 

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);
David Zaslavsky
This is great thanks, although would aa bi.truncateAt() have been too much to ask for? :)
Xenph Yan
+2  A: 

You can use regular expression

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