2.6. Stripping and Trimming a String

Problem

You need to strip or trim a string of extraneous whitespace, control characters, or other specified characters.

Solution

StringUtils.trim() takes a string and removes every whitespace and control character from the beginning and the end:

String test1 = " \a\r Testing 1 2 3 ";
String test2 = " \r\n ";
 
String trimTest1 = StringUtils.trim( test1 );
String trimTest2 = StringUtils.trimToNull( test2 );

System.out.println( trimTest1 );
System.our.println( trimTest2 );

This code produces the following result. The test1 variable is trimmed of leading and trailing whitespace, and the test2 variable is trimmed to null:

Testing 1 2 3
null

Discussion

A control character is defined as all characters below 32 on the ASCII table—everything from 0 (NUL) to 31 (unit separator). StringUtils.trim( ) delegates to the trim( ) function on String and gracefully handles null. When you pass a null to StringUtils.trim( ), it returns a null.

Stripping a string

If a string contains leading and trailing characters to be removed, you can remove them with StringUtils.strip( ). The strip( ) method differs from trim( ) in that you can specify a set of characters to strip from the beginning and end of a string. In this example, dashes and asterisks are stripped from the start and end of a string:

String original = "-------***---SHAZAM!---***-------";
String stripped = StringUtils.strip( original, "-*" );

System.out.println( "Stripped: " + stripped )

This produces the ...

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.