Remove any whitespace from start and end of a String in Java



This example shows how to remove any whitespace from the beginning and end of a String. This can be done with standard Java using the trim() method of the String class, but we’ll also show how to do it with the StringUtils class of the Apache Commons Lang library, since it is null-safe which means that even if you pass in a null value to them it won’t throw a NullPointerException but rather just return null. The standard Java way of doing this is not null-safe and will throw a NullPointerException if the parameter to the method is null.

Using the StringUtils class it is actually possible to use two methods. The strip() method is the one that should be used since it targets whitespace. The trim() method removes any control character with a value <= 32, but that includes whitespace also. We add an exclamation mark at the end of the values to be sure there are now whitespaces left.

Output from the code above:

The strip() method of StringUtils also have an overloaded method that takes two arguments, the string to be stripped and another string containing the characters that should be stripped from start and end:

Output from the code above is this. Note that only the trailing 'c' is removed, not the center one:

Both trim() and strip() methods of the StringUtils class have a method that returns an empty string if the argument passed to it is null (instead of returning null). The difference is shown below:

Output:







Search for more Java info on this site here:
Custom Search


Please type any questions here.