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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With