public static String safeTruncate ( final String value , final int length , final String filler ) { validate ( value , NULL_STRING_PREDICATE , NULL_STRING_MSG_SUPPLIER ) ; if ( length == 0 ) { return "" ; } if ( length >= value . length ( ) ) { return value ; } String [ ] words = words ( value ) ; StringJoiner result = new StringJoiner ( " " ) ; int spaceCount = 0 ; for ( String word : words ) { if ( result . length ( ) + word . length ( ) + filler . length ( ) + spaceCount > length ) { break ; } else { result . add ( word ) ; spaceCount ++ ; } } return append ( result . toString ( ) , filler ) ; }
Truncate the string securely not cutting a word in half . It always returns the last full word .