24

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

http://stackoverflow.com/questions/ask

n' I wanna change it to:

http://stackoverflow.com/questions/

How can I do it.

PeeHaa
  • 69,318
  • 57
  • 185
  • 258
Aybek Kokanbekov
  • 514
  • 2
  • 7
  • 27
  • 2
    Have you tried anything? At least gone through the String API? – Rohit Jain Aug 09 '13 at 08:21
  • 4
    Use String.lastIndexOf(String) to find the last slash and then select the substring till there...? Takes about 10 seconds to find in the String API... – sheltem Aug 09 '13 at 08:21
  • one line solution. http://stackoverflow.com/questions/5437158/remove-a-trailing-slash-from-a-stringchanged-from-url-type-in-java/27942845#27942845 – Zar E Ahmer Jan 14 '15 at 12:22

4 Answers4

57

You can try this

    String str="http://stackoverflow.com/questions/ask";
    int index=str.lastIndexOf('/');
    System.out.println(str.substring(0,index));
Ruchira Gayan Ranaweera
  • 33,712
  • 16
  • 72
  • 110
19

IF you want to get the last value from the 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"

RCR
  • 489
  • 8
  • 15
5

Try using String#lastIndexOf()

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

String result = yourString.subString(0,yourString.lastIndexOf("/"));
Suresh Atta
  • 118,038
  • 37
  • 189
  • 297
1
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)
    }
} 
Sai Aditya
  • 2,266
  • 1
  • 13
  • 16