我有一个在JAVA中移除URL最后一个斜杠后面的所有内容的问题。 例如,我的URL:
http://stackoverflow.com/questions/ask
我想要将它改变成:
http://stackoverflow.com/questions/
我该如何做到这一点。
我有一个在JAVA中移除URL最后一个斜杠后面的所有内容的问题。 例如,我的URL:
http://stackoverflow.com/questions/ask
我想要将它改变成:
http://stackoverflow.com/questions/
我该如何做到这一点。
你可以尝试这个
String str="http://stackoverflow.com/questions/ask";
int index=str.lastIndexOf('/');
System.out.println(str.substring(0,index));
如果您想从URL中获取最后一个值
String str="http://stackoverflow.com/questions/ask";
System.out.println(str.substring(str.lastIndexOf("/")));
结果将会是"/ask"
如果你想要获取最后一个正斜杠后面的值
String str="http://stackoverflow.com/questions/ask";
System.out.println(str.substring(str.lastIndexOf("/") + 1));
结果将是“ask”
返回指定字符在此字符串中最后一次出现的索引。
String result = yourString.subString(0,yourString.lastIndexOf("/"));
String result = http://stackoverflow.com/questions/ask
,则在字符串result
中输出ask
。 - Santhoshif (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)
}
}