Use StringUtils.abbreviate()
. Supply the string to abbreviate, and the maximum allowed length
for the abbreviation. The following example will abbreviate the supplied
text messages to 10 characters:
String test = "This is a test of the abbreviation." String test2 = "Test" System.out.println( StringUtils.abbreviate( test, 10 ) ); System.out.println( StringUtils.abbreviate( test2, 10 ) );
Here is the output of two string abbreviations:
This is... Test
StringUtils.abbreviate( )
takes
a string and abbreviates it, if necessary. When abbreviating to 20
characters, if the text is less than 20 characters, the method simply
returns the original text. If the text is greater than 20 characters,
the method displays 17 characters followed by three ellipses.
Abbreviating a piece of text to 20 characters guarantees that the text
will occupy 20 characters or less:
String message = "Who do you think you are?"; String abbrev = StringUtils.abbreviate( message, 20 ); String message2 = "Testing"; String abbrev2 = StringUtils.abbreviate( message, 40 ); System.out.println( "Subject: " + message ); System.out.println( "Subject2: " + messages2);
This simple example abbreviates the first message variable,
message
, to "Who do you think...?"
The second message variable, message2
, is not affected by the abbreviation
because it is less than 40 characters long; abbrev2
will equal the contents of message2
.
StringUtils.abbreviate( )
can
also abbreviate text at an offset within a string. If you are writing an
application that searches for a given word and prints that word out in
context, you can use the StringUtils.abbreviate( )
method to print the
context in which a word appears:
String message = "There was a palpable sense that the rest of the world " + "might, one day, cease to exist. In the midst of the " + "confusion - the absence of firm ground - something would " + "fail to recover. The whole city is still, in a way, " + "holding it's breath, hoping the the worst has come and " + "gone."; int index = message.indexOf( "ground" ); int offset = index - 20; int width = 20 + message.length( ); String context = StringUtils.abbreviate(message, offset, width); System.out.println( "The word 'ground' in context: " + context );
The output of this example is:
The word 'ground' in context: ... absence of firm ground, something would...
This code attempts to locate "ground." Once the index of the word
has been located, an offset abbreviation is used to show the context of
the word. The offset
parameter tells
StringUtils.abbreviate( )
to start at
a specific index in the string. Once the index of "ground" has been
found, an offset and a width are computed to print 20 characters before
and after the word "ground."
If an offset is less than four, output will start from the beginning of a string. If the offset is greater than four, the first three characters will be ellipses.