Remove a trailing slash from a string(changed from url type) in JAVA

Solution 1:

There are two options: using pattern matching (slightly slower):

s = s.replaceAll("/$", "");

or:

s = s.replaceAll("/\\z", "");

And using an if statement (slightly faster):

if (s.endsWith("/")) {
    s = s.substring(0, s.length() - 1);
}

or (a bit ugly):

s = s.substring(0, s.length() - (s.endsWith("/") ? 1 : 0));

Please note you need to use s = s..., because Strings are immutable.

Solution 2:

This should work better:

url.replaceFirst("/*$", "")

Solution 3:

You can achieve this with Apache Commons StringUtils as follows:

String s = "http://almaden.ibm.com/";
StringUtils.removeEnd(s, "/")