Below is the method that I use to trim long lines in my web folders. The soft boolean , as you put it, if set to true , the last word will be saved. This is the most concise way to do this so that I can come up with what uses a StringBuffer, which is much more efficient than re-creating a string that is immutable.
public static String trimString(String string, int length, boolean soft) { if(string == null || string.trim().isEmpty()){ return string; } StringBuffer sb = new StringBuffer(string); int actualLength = length - 3; if(sb.length() > actualLength){
Update
I changed the code so that ... was added to the StringBuffer to prevent unnecessary String creation implicitly, which is slow and wasteful.
Note. escapeHtml is a static import from apache commons:
import static org.apache.commons.lang.StringEscapeUtils.escapeHtml;
You can remove it, and the code should work the same.
Ali
source share