Remove characters from the end of a String in Java using Apache Commons StringUtils class



This example shows how to use the StringUtils class of the Apache Commons Lang library to remove characters form the end of a String.
To accomplish that we use the method chomp() of the StringUtils class to which we send the String to be altered and a character sequence of the characters we want to be removed from the end of it.
The code below shows an example. The String s contains numbers separated by a comma and a whitespace. We want to get rid of them at the end of the String so we call chomp that returns a new String with the desired format:

The output from the code is:

There is an overloaded chomp method in the StringUtils class that doesn’t take a character sequence. That method removes any new line characters at the end of the String. New line characters include ‘\r’, ‘\n’ and ‘\r\n’ (carriage return and line feed).

The output from the above code is:

If you just want to remove the last character of a String, no matter what it is, use the chop() method instead:

Output:







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


Please type any questions here.