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条回答
ら.Afraid
2楼-- · 2019-04-17 20:24

simple method in java

String removeLastSlash(String url) {
    if(url.endsWith("/")) {
        return url.substring(0, url.lastIndexOf("/"));
    } else {
        return url;
    }
}
查看更多
淡お忘
3楼-- · 2019-04-17 20:24

If you are a user of Apache Commons Lang you can take profit of the chomp method located in StringUtils

String s = "http://almaden.ibm.com/";

StringUtils.chomp(s,File.separatorChar+"")

查看更多
家丑人穷心不美
4楼-- · 2019-04-17 20:31
   if (null != str && str.length > 0 )
    {
        int endIndex = str.lastIndexOf("/");
        if (endIndex != -1)  
        {
            String newstr = str.subString(0, endIndex); // not forgot to put check if(endIndex != -1)
        }
    }  
查看更多
登录 后发表回答