I need to trim a String in java so that:
The quick brown fox jumps over the laz dog.
becomes
The quick brown…
In the example above, I’m trimming to 12 characters. If I just use substring I would get:
The quick br…
I already have a method for doing this using substring, but I wanted to know what is the fastest (most efficient) way to do this because a page may have many trim operations.
The only way I can think off is to split the string on spaces and put it back together until its length passes the given length. Is there an other way? Perhaps a more efficient way in which I can use the same method to do a “soft” trim where I preserve the last word (as shown in the example above) and a hard trim which is pretty much a substring.
Thanks,
Below is a method I use to trim long strings in my webapps.
The “soft”
booleanas you put it, if set totruewill preserve the last word.This is the most concise way of doing it that I could come up with that uses a StringBuffer which is a lot more efficient than recreating a string which is immutable.
Update
I’ve changed the code so that the
...is appended in the StringBuffer, this is to prevent needless creations ofStringimplicitly which is slow and wasteful.Note:
escapeHtmlis 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.