Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove string after last occurrence of a character

Tags:

java

In my application, I am appending a string to create path to generate a URL. Now I want to remove that appended string on pressing back button.

Suppose this is the string:

/String1/String2/String3/String4/String5 

Now I want a string like this:

/String1/String2/String3/String4/ 

How can I do this?

like image 812
Krishna Suthar Avatar asked May 31 '12 06:05

Krishna Suthar


People also ask

How do you delete after last occurrence of a character?

The indexOf method returns the index of the first occurrence of a character in the string. If you need to remove everything after the last occurrence of a specific character, use the lastIndexOf method.

How do you delete a string after a certain character?

The substr() and strpos() function is used to remove portion of string after certain character. strpos() function: This function is used to find the first occurrence position of a string inside another string. Function returns an integer value of position of first occurrence of string.

How do I remove the last occurrence of a character from a string in Python?

rstrip. The string method rstrip removes the characters from the right side of the string that is given to it. So, we can use it to remove the last element of the string. We don't have to write more than a line of code to remove the last char from the string.

How do I remove the last occurrence of a string in Java?

Text. Remove(Regex.//Substring(1, node. Text. IndexOf(" (")); else value = node.


2 Answers

You can use lastIndexOf() method for same with

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)     } }   
like image 50
Dheeresh Singh Avatar answered Sep 21 '22 08:09

Dheeresh Singh


String whatyouaresearching = myString.substring(0, myString.lastIndexOf("/")) 
like image 30
rsan Avatar answered Sep 24 '22 08:09

rsan