This post will discuss how to implement the trim() method in Java.

The trim() method in Java is a built-in method provided by the String class that removes leading and trailing spaces from a string. It checks for whitespace characters before and after the string, and if it exists, it removes it and returns the modified string. To implement the trim() method in Java, or to achieve a similar functionality, we can use one of the following methods:

1. Using String.replaceAll() method

We can use the String class replaceAll() method to implement the trim() method in Java. The replaceAll() method takes a regular expression and replaces each substring of this string that matches the regex with the specified replacement. To perform the trim operation, we can use the regex "^\s+|\s+$" to match with the leading and trailing spaces, and replace them with an empty string. Since String is immutable in Java, we can’t perform trim operation in-place. To change the original string, we might need to assign the trimmed string back to the original variable. For example:

Download  Run Code

2. Using a loop

We can even write our own utility methods, which doesn’t involve using any regex. The idea is to use a loop to iterate over the string from left to right and find the index of the first non-whitespace character. Similary, use another loop to iterate over the string from right to left, and find the index of the last non-whitespace character. Then use the substring() method to return a copy of the string between those indices. For example:

Download  Run Code

3. Using Apache Commons Lang

The StringUtils class from Apache Commons Lang library provides various utility methods for manipulating strings, including a trim() method that behaves exactly like the trim() method of the String class. It strips whitespace from the start and end of a string. To use it, we need to import the org.apache.commons.lang3.StringUtils class and then call it as follows:

Download Code

4. Using Guava class

Finally, we can leverage Guava CharMatcher class that has several methods for matching and manipulating characters in strings. It provides a trimFrom() method that removes leading and trailing characters from a string which satisfy a given condition. To use this method, we need to include the guava jar in the project, and then invoke this method as follows:

Download Code

That’s all about implementing the trim() method in Java.