Implement trim() method in Java

In this post, we will see how to trim leading and trailing whitespace in Java.

 

1. String.trim()

Simplest and standard solution is to use the trim() function provided by the String class. Note that since String are immutable in Java, we can’t perform trim operation in-place. In order to change the original string, we might need to assign the trimmed string back to the original variable.

 

Download   Run Code

Output:

:Trim Me:

 

2. String.replaceAll()

We can make use of String class replaceAll() method to implement the trim operation 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:

:Trim Me:

 

3. Naive

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

 

Download   Run Code

Output:

:Trim Me:

 

4. Apache Commons Lang

Finally, we can can leverage Apache Commons Lang StringUtils class strip() method which strips whitespace from start and end of a String.

 

 

 
Related Post: Remove leading and trailing whitespace in Java (left trim and right trim)

 
Thanks for reading.

Please use our online compiler to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 



Leave a Reply

avatar
  Subscribe  
Notify of