Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove string after last slash in JAVA [duplicate]

Tags:

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.

like image 594
Aybek Kokanbekov Avatar asked Aug 09 '13 08:08

Aybek Kokanbekov


People also ask

How do you remove the last slash from a string in Java?

replaceAll("/","");

How do you remove the last slash from a string?

Use the String. replace() method to remove a trailing slash from a string, e.g. str. replace(/\/+$/, '') . The replace method will remove the trailing slash from the string by replacing it with an empty string.

How do slashes work in Java?

A character preceded by a backslash (\) is an escape sequence and has a special meaning to the compiler. The following table shows the Java escape sequences. Inserts a tab in the text at this point. Inserts a backspace in the text at this point.


3 Answers

You can try this

    String str="http://stackoverflow.com/questions/ask";     int index=str.lastIndexOf('/');     System.out.println(str.substring(0,index)); 
like image 84
Ruchira Gayan Ranaweera Avatar answered Sep 20 '22 22:09

Ruchira Gayan Ranaweera


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"

like image 23
RCR Avatar answered Sep 18 '22 22:09

RCR


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("/"));
like image 40
Suresh Atta Avatar answered Sep 20 '22 22:09

Suresh Atta