How can I trim the leading or trailing characters from a string in java?
For example, the slash character "/" - I'm not interested in spaces, and am looking to trim either leading or trailing characters at different times.
To remove leading and trailing spaces in Java, use the trim() method. This method returns a copy of this string with leading and trailing white space removed, or this string if it has no leading or trailing white space.
Use the Python string rstrip(chars) method to return a copy of a string with the trailing characters removed. Use the rstrip() method without argument to return a copy of a string with the trailing whitespace removed.
In the StringUtils class, we have the methods stripStart() and stripEnd(). They remove leading and trailing characters respectively.
L'string' - a leading string to appear at the beginning of the character or numeric data column. T'string' - a trailing string to appear at the end of the character or numeric data column.
You could use
Leading:
System.out.println("//test/me".replaceAll("^/+", ""));
Trailing:
System.out.println("//test/me//".replaceAll("/+$", ""));
You can use Apache StringUtils.stripStart to trim leading characters, or StringUtils.stripEnd to trim trailing characters.
For example:
System.out.println(StringUtils.stripStart("//test/me", "/"));
will output:
test/me
Note that if for some reason you can't use the whole StringUtils library, you could just rip out the relevant parts, as detailed here:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With