If the source line has a character at position 60 (char 61st), that is, you are going to cut the word or start word, look back and turn on position 59 (char 60th), and stop when you find a place. Then we can fine-tune the string at that location. If the string is no longer than 60 characters, we simply return it as is.
public void truncateTest() { System.out.println(truncateTo("Bangladesh 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. ", 60)); System.out.println(truncateTo("Bangladesh first day.", 60)); System.out.println(truncateTo("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.", 60)); } public String truncateTo(String originalText, int len) { if (originalText.length() > len) { if (originalText.charAt(len) != ' ') { for (int x=len-1;x>=0;x--) { if (Character.isWhitespace(originalText.charAt(x))) { return originalText.substring(0, x); } } }
Results...
Bangladesh first day of Test cricket on Indian soil has Bangladesh first day. They end the day having conceded 71 runs in the last 10
I think I got the logic of the index + 1 / -1 :)
Summing up the Indian batting, Pujara was an embodiment of patience, Vijay's shots were despised, and the skipper Kolya crowned this with a manifestation of complete contempt in what turned out to be the complete dominance of the Indian team.
source share