天天看點

java斜杠字元串轉date,從JAVA中的字元串中删除尾随斜杠(已更改為url類型)

java斜杠字元串轉date,從JAVA中的字元串中删除尾随斜杠(已更改為url類型)

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

}

else LOGGER.info("Doesnt end with trailing slash");

But neither work.

解決方案

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.