27

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
  • 71,436
  • 58
  • 190
  • 262
Aybek Kokanbekov
  • 575
  • 2
  • 8
  • 29
  • 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

61

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
  • 34,993
  • 17
  • 75
  • 115
20

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
  • 529
  • 9
  • 15
6

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
  • 120,458
  • 37
  • 198
  • 307
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,353
  • 1
  • 14
  • 16