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.
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.
You can try this
String str="http://stackoverflow.com/questions/ask";
int index=str.lastIndexOf('/');
System.out.println(str.substring(0,index));
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"
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("/"));
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)
}
}