在JAVA中从字符串(已更改为url类型)中删除结尾的斜杠 [英] Remove a trailing slash from a string(changed from url type) in JAVA

查看:488
本文介绍了在JAVA中从字符串(已更改为url类型)中删除结尾的斜杠的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从Java中的字符串中删除斜杠.

I want to remove the trailing slash from a string in Java.

我想检查字符串是否以url结尾,如果是,我想将其删除.

I want to check if the string ends with a url, and if it does, i want to remove it.

这就是我所拥有的:

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

但都不行.

推荐答案

有两种选择:使用模式匹配(速度稍慢):

There are two options: using pattern matching (slightly slower):

s = s.replaceAll("/$", "");

或:

s = s.replaceAll("/\\z", "");

并使用if语句(速度稍快):

And using an if statement (slightly faster):

if (s.endsWith("/")) {
    s = s.substring(0, s.length() - 1);
}

或(有点难看):

s = s.substring(0, s.length() - (s.endsWith("/") ? 1 : 0));

请注意,您需要使用s = s...,因为字符串是不可变的.

Please note you need to use s = s..., because Strings are immutable.

这篇关于在JAVA中从字符串(已更改为url类型)中删除结尾的斜杠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆