Given an input string, a
StringLimiter
produces a representation of that string limited by a defined max length. If the defined max length is shorter than the original string, "..." is used at the end of the limited string to show that the whole input string could not be represented.
If the input string is shorter than the defined max length, the produced string representation will be identical to the input string.
A StringLimiter
can work in one of two modes (assuming that the input string is longer than the defined max length):
- Use word boundaries when deciding where to cut off the string: In this mode, a
BreakIterator
as returned from the method {@link #getWordIterator()} is used todetect word boundaries. This is the default behavior. Note that in this mode, the resulting string representation may be shorter than the defined max length. - Brute force: In this mode the input string will be cut off so that adding "..." to the starting fragment produces a string of length exactly equal to the defined max length.
An additional note about the first mode: If the input string starts with a single word that is longer than the defined max length, the returned string representation is derived using the brute force mode.
A couple of examples:
StringLimiter limiter = new StringLimiter("The quick brown fox jumps over the lazy dog"); limiter.setBreakAtWordBoundaries(true); assert limiter.getLimitedString(16).equals("The quick ..."); limiter.setBreakAtWordBoundaries(false); assert limiter.getLimitedString(16).equals("The quick bro..."); assert limiter.getLimitedString(1000) == limiter.getInputString(); limiter = new StringLimiter("Floccinaucinihilipilification is a famously long word meaning 'the action of estimating as worthless'"); limiter.setBreakAtWordBoundaries(true); assert limiter.getLimitedString(16).equals("Floccinaucini..."); limiter.setBreakAtWordBoundaries(false); assert limiter.getLimitedString(16).equals("Floccinaucini...");
@author Torgil Zethson
@since 1.3.0