This post will discuss how to remove leading and trailing whitespace in Java. In ASCII, whitespace characters are space (' '), tab ('\t'), carriage return ('\r'), newline ('\n'), vertical tab ('\v') and form feed ('\f').

1. Using String.replaceAll() method

We can use of String class replaceAll() method to implement left and right trim in Java. The replaceAll() method takes a regular expression and replaces each substring of this string that matches the regex with the specified replacement.

Download  Run Code

Output:

Left Trim :Hello World :
Right Trim: Hello World:

 
For better performance, we recommend compiling the regular expression first, as shown below:

Download  Run Code

Output:

Left Trim :Hello World :
Right Trim: Hello World:

2. Naive solution

We can even write our own utility methods, which doesn’t involve using any regex and performs comparatively faster.

Download  Run Code

Output:

Left Trim :Hello World :
Right Trim: Hello World:

3. Using Apache Commons Lang

Finally, we can leverage Apache Commons Lang StringUtils class stripStart() and stripEnd() utility methods, which can strip the specified set of whitespace characters from the start and end of a string, respectively.

Download Code

That’s all about removing leading and trailing whitespace in Java.