I want to remove the trailing slash from a string in Java.
I want to check if the string ends with a url, and if it does, i want to remove it.
Here is what I have:
String s = "http://almaden.ibm.com/";
s= s.replaceAll("/","");
and this:
String s = "http://almaden.ibm.com/";
length = s.length();
--length;
Char buff = s.charAt((length);
if(buff == '/')
{
LOGGER.info("ends with trailing slash");
/*how to remove?*/
}
else LOGGER.info("Doesnt end with trailing slash");
But neither work.
There are two options: using pattern matching (slightly slower):
or:
And using an if statement (slightly faster):
or (a bit ugly):
Please note you need to use
s = s...
, because Strings are immutable.Easiest way ...
This should work better:
As its name indicates, the replaceAll method replaces all the occurrences of the searched string with the replacement string. This is obviously not what you want. You could have found it yourself by reading the javadoc.
The second one is closer from the truth. By reading the javadoc of the String class, you'll find a useful method called substring, which extracts a substring from a string, given two indices.
url.replaceAll("/$", "")
the$
matches the end of a string so it replaces the trailing slash if it exists.a more compact way:
regexp ^/ replaces the first, /$ replaces the last