Remove a trailing slash from a string(changed from

2019-04-17 19:38发布

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.

9条回答
成全新的幸福
2楼-- · 2019-04-17 20:05

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.

查看更多
爱情/是我丢掉的垃圾
3楼-- · 2019-04-17 20:08

Easiest way ...

String yourRequiredString = myString.subString(0,myString.lastIndexOf("/"));
查看更多
在下西门庆
4楼-- · 2019-04-17 20:09

This should work better:

url.replaceFirst("/*$", "")
查看更多
神经病院院长
5楼-- · 2019-04-17 20:12

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.

查看更多
Evening l夕情丶
6楼-- · 2019-04-17 20:13

url.replaceAll("/$", "") the $ matches the end of a string so it replaces the trailing slash if it exists.

查看更多
来,给爷笑一个
7楼-- · 2019-04-17 20:16

a more compact way:

String pathExample = "/test/dir1/dir2/";

String trimmedSlash = pathExample.replaceAll("^/|/$","");

regexp ^/ replaces the first, /$ replaces the last

查看更多
登录 后发表回答