在JAVA中从字符串(从url类型更改)中删除尾部斜杠
我想从 Java 中的字符串中删除尾部斜杠。
我想检查字符串是否以 url 结尾,如果是,我想删除它。
这是我所拥有的:
String s = "http://almaden.ibm.com/";
s= s.replaceAll("/","");
和这个:
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");
但两者都不起作用。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(11)
有两个选项: 使用模式匹配(稍慢):
或:
使用 if 语句(稍快):
或(有点难看):
请注意,您需要使用
s = s...
,因为字符串是不可变的。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.这应该效果更好:
This should work better:
您可以使用 Apache Commons StringUtils 如下:
You can achieve this with Apache Commons StringUtils as follows:
url.replaceAll("/$", "")
$
匹配字符串的末尾,因此它会替换尾部斜杠(如果存在)。url.replaceAll("/$", "")
the$
matches the end of a string so it replaces the trailing slash if it exists.java中的简单方法
simple method in java
正如其名称所示,replaceAll 方法将所有出现的搜索字符串替换为替换字符串。这显然不是你想要的。您可以通过阅读 javadoc 自己找到它。
第二个更接近事实。通过阅读 String 类的 javadoc,您将发现一个名为 substring 的有用方法,该方法在给定两个索引的情况下从字符串中提取子字符串。
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.
最简单的方法...
Easiest way ...
更紧凑的方式:
regexp ^/ 替换第一个,/$ 替换最后一个
a more compact way:
regexp ^/ replaces the first, /$ replaces the last
如果您是 Apache Commons Lang 的用户,您可以利用位于 StringUtils 中的 chomp 方法
If you are a user of Apache Commons Lang you can take profit of the chomp method located in StringUtils
科特林方面
Kotlin side