在 JAVA 中删除最后一个斜杠后的字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18142671/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 22:42:32  来源:igfitidea点击:

Remove string after last slash in JAVA

javaurl

提问by Aybek Kokanbekov

I have a problem with removing everything after the last slash of URL in JAVA For instance, I have URL:

我在 JAVA 中删除 URL 的最后一个斜杠后的所有内容时遇到问题例如,我有 URL:

http://stackoverflow.com/questions/ask

n' I wanna change it to:

n' 我想把它改成:

http://stackoverflow.com/questions/

How can I do it.

我该怎么做。

采纳答案by Ruchira Gayan Ranaweera

You can try this

你可以试试这个

    String str="http://stackoverflow.com/questions/ask";
    int index=str.lastIndexOf('/');
    System.out.println(str.substring(0,index));

回答by Suresh Atta

Try using String#lastIndexOf()

尝试使用String#lastIndexOf()

Returns the index within this string of the last occurrence of the specified character.

返回此字符串中最后一次出现的指定字符的索引。

String result = yourString.subString(0,yourString.lastIndexOf("/"));

回答by Sai Aditya

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

回答by RCR

IF you want to get the last value from the uRL

如果您想从 uRL 中获取最后一个值

String str="http://stackoverflow.com/questions/ask";
System.out.println(str.substring(str.lastIndexOf("/")));

Result will be "/ask"

结果将是“/询问”

If you want value after last forward slash

如果你想要最后一个正斜杠后的值

String str="http://stackoverflow.com/questions/ask";
System.out.println(str.substring(str.lastIndexOf("/") + 1));

Result will be "ask"

结果将是“询问”