Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cut string in java without breaking the middle of word [duplicate]

How can i truncate a text whithout cut in the middle of a word?

For exemple, I have the string :

"A totally fresh and new approach to life itself emerges. Once again, you’re off to a good start, willing to do that little bit extra in your result-oriented frame of mind. It’s not the amount of effort but the results that matter to you. You also gain much in the depth of the romance and emotional bonds in your life. This is a good time for self-improvement programs or philanthropy, alms-giving and charity."

If i cut it, i want to cut like this :

"A totally fresh and new approach to life itself emerges. Once again, you’re off to a good start, willing to do that little bit extra in your result-oriented frame of mind. It’s not the amount of effort but the results that matter to you. You also gain much in the depth of the romance and"

And not :

"A totally fresh and new approach to life itself emerges. Once again, you’re off to a good start, willing to do that little bit extra in your result-oriented frame of mind. It’s not the amount of effort but the results that matter to you. You also gain much in the depth of the romance and emoti"

like image 575
Bitu Patel Avatar asked Sep 07 '25 16:09

Bitu Patel


2 Answers

In this method pass your string and last index till you want to truncate.

public String truncate(final String content, final int lastIndex) {
    String result = content.substring(0, lastIndex);
    if (content.charAt(lastIndex) != ' ') {
        result = result.substring(0, result.lastIndexOf(" "));
    }
    return result;
}
like image 97
Ashish Aggarwal Avatar answered Sep 10 '25 01:09

Ashish Aggarwal


WordUtils.wrap(String str, int wrapLength) from Apache Commons.

like image 44
Adam Stelmaszczyk Avatar answered Sep 10 '25 01:09

Adam Stelmaszczyk