2.3. Abbreviating Strings
Problem
You want to abbreviate a string.
Solution
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
Discussion
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( ...
Get Jakarta Commons Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.