Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove last occurrence of a string in a string

Tags:

string

c#

I have a string that is of nature

  • RTT(50)
  • RTT(A)(50)
  • RTT(A)(B)(C)(50)

What I want to is to remove the last () occurrence from the string. That is if the string is - RTT(50), then I want RTT only returned. If it is RTT(A)(50), I want RTT(A) returned etc.

How do I achieve this? I currently use a substring method that takes out any occurrence of the () regardless. I thought of using:

Regex.Matches(node.Text, "( )").Count

To count the number of occurrences so I did something like below.

 if(Regex.Matches(node.Text, "( )").Count > 1)
      //value = node.Text.Remove(Regex.//Substring(1, node.Text.IndexOf(" ("));
 else
     value = node.Text.Substring(0, node.Text.IndexOf(" ("));

The else part will do what I want. However, how to remove the last occurrence in the if part is where I am stuck.

like image 900
Nuru Salihu Avatar asked May 09 '14 03:05

Nuru Salihu


People also ask

How do you remove the last occurrence of a character?

To remove the last occurrence of a character in a string:Use the lastIndexOf() method to get the index of the last occurrence of the character. Concatenate the results from 2 calls to the slice method, excluding the character at the specific index.

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 you find the last occurrence of a substring in a string?

The rfind() method finds the last occurrence of the specified value. The rfind() method returns -1 if the value is not found. The rfind() method is almost the same as the rindex() method.


2 Answers

The String.LastIndexOf method does what you need - returns the last index of a char or string.

If you're sure that every string will have at least one set of parentheses:

var result = node.Text.Substring(0, node.Text.LastIndexOf("("));

Otherwise, you could test the result of LastIndexOf:

var lastParenSet = node.Text.LastIndexOf("(");

var result =
    node.Text.Substring(0, lastParenSet > -1 ? lastParenSet : node.Text.Count());
like image 109
Grant Winney Avatar answered Oct 16 '22 04:10

Grant Winney


This should do what you want :

your_string = your_string.Remove(your_string.LastIndexOf(string_to_remove));

It's that simple.

like image 41
Sebriniel Avatar answered Oct 16 '22 04:10

Sebriniel