Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do truncate string of certain length but include complete words after truncation

I want to truncate substring from string upto 60 characters , but also want to get complete words within substring. Here is what I am trying.

String originalText =" Bangladesh's first day of Test cricket on Indian soil has not been a good one. They end the day having conceded 71 runs in the last 10 overs, which meant they are already staring at a total of 356. M Vijay was solid and languid as he made his ninth Test century and third of the season. ";
String afterOptimized=originalText.substring(0, 60);
System.out.println("This is text . "+afterOptimized);

Here is output

This is text .  Bangladesh's first day of Test cricket on Indian soil has n

However mine requirement is to not cut the words in between.How do I know there is complete words or not after 60 characters.

like image 802
glen maxwell Avatar asked Feb 10 '17 02:02

glen maxwell


1 Answers

You can use regular expression for this, taking up to 60 characters and ending at word boundary:

Pattern pattern = Pattern.compile("(.{1,60})(\\b|$)(.*)");
Matcher m = pattern.match(originalText);
If (m.matches())
    afterOptimized = m.group(1);

Or, in a loop:

Pattern pattern = Pattern.compile("\\s*(.{1,60})(\\b|$)");
Matcher m = pattern.matcher(originalText);
int last = 0;
while (m.find()) {
    System.out.println(m.group(1));
    last = m.end();
}
if (last != originalText.length())
    System.out.println(originalText.substring(last));

You may want to replace \b with \s if you want to wrap only at white space instead of word boundary (which may wrap before comma, dots etc).

like image 85
Zbynek Vyskovsky - kvr000 Avatar answered Oct 23 '22 20:10

Zbynek Vyskovsky - kvr000