Delete line after last slash in JAVA

I have a problem with deleting everything after the last braid of URLs in JAVA For example, I have a URL:

http://stackoverflow.com/questions/ask 

n 'I want to change it to:

 http://stackoverflow.com/questions/ 

How can i do this.

+7
java url
source share
4 answers

You can try this

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

IF you want to get the last value from uRL

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

The result will be "/ ask"

If you need a value after the last slash

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

The result will be "ask"

+5
source share

Try using String # lastIndexOf ()

Returns the index on this line of the last occurrence of the specified character.

 String result = yourString.subString(0,yourString.lastIndexOf("/")); 
+4
source share
 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) } } 
+1
source share

All Articles