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

妖精的绣舞 提交于 2019-12-22 01:23:51

问题


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.


回答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.




回答2:


This should work better:

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



回答3:


simple method in java

String removeLastSlash(String url) {
    if(url.endsWith("/")) {
        return url.substring(0, url.lastIndexOf("/"));
    } else {
        return url;
    }
}



回答4:


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




回答5:


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.




回答6:


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+"")




回答7:


a more compact way:

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

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

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




回答8:


You can achieve this with Apache Commons StringUtils as follows:

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



回答9:


   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)
        }
    }  



回答10:


Easiest way ...

String yourRequiredString = myString.subString(0,myString.lastIndexOf("/"));


来源:https://stackoverflow.com/questions/5437158/remove-a-trailing-slash-from-a-stringchanged-from-url-type-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!