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
 Testing 1 2 3 ";
String test2 = " 
 ";
 
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 following output:

Stripped: SHAZAM!

Trimming to null

Use trimToNull( ) to test if a given parameter is present. Take the following servlet code as an example:

public void doGet(HttpServletRequest request, HttpServletResponse response)
    throws IOException, ServletException {

    String companyName = 
        StringUtils.trimToNull( request.getParameter("companyName") );
    if( companyName != null ) {
        response.getWriter( ).write( "You supplied a company name!" );
    }
}

Using StringUtils reduces code complexity incrementally—four or five lines of code at a time. Testing for the absence or emptiness of a string usually entails checking to see if a string is empty or of zero length, and because a string could be null, you always need to check for null to avoid throwing a NullPointerException. In this last example, empty has the same meaning as null—the StringUtils.trimToNull( ) method takes a string as a parameter, and if it is null or empty, the method returns a null.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.235.62