Search code examples
javaandroidregex

cut string in java without breaking the middle of word


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"


Solution

  • 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;
    }