Nuru Salihu
Nuru Salihu

Reputation: 4928

Remove last occurrence of a string in a string

I have a string that is of nature

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.

Upvotes: 18

Views: 37227

Answers (6)

Sebriniel
Sebriniel

Reputation: 181

This should do what you want :

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

It's that simple.

Upvotes: 14

Ravindra Kumar
Ravindra Kumar

Reputation: 601

It's very simple. You can easily achieve like this:

string a=RTT(50);

string res=a.substring (0,a.LastIndexOf("("))

Upvotes: 2

angrywill
angrywill

Reputation: 11

As an extention:

namespace CustomExtensions
{
    public static class StringExtension
    {
        public static string ReplaceLastOf(this string str, string fromStr, string toStr)
        {
            int lastIndexOf = str.LastIndexOf(fromStr);
            if (lastIndexOf < 0)
                return str;

            string leading = str.Substring(0, lastIndexOf);
            int charsToEnd = str.Length - (lastIndexOf + fromStr.Length);
            string trailing = str.Substring(lastIndexOf+fromStr.Length, charsToEnd);

            return leading + toStr + trailing;
        }
   }
}

Use:

string myFavColor = "My favourite color is blue";
string newFavColor = myFavColor.ReplaceLastOf("blue", "red");

Upvotes: 1

Ahmad Mageed
Ahmad Mageed

Reputation: 96477

There are a couple of different options to consider.

LastIndexOf

Get the last index of the ( character and take the substring up to that index. The downside of this approach is an additional last index check for ) would be needed to ensure that the format is correct and that it's a pair with the closing parenthesis occurring after the opening parenthesis (I did not perform this check in the code below).

var index = input.LastIndexOf('(');
if (index >= 0)
{
    var result = input.Substring(0, index);
    Console.WriteLine(result);
}

Regex with RegexOptions.RightToLeft

By using RegexOptions.RightToLeft we can grab the last index of a pair of parentheses.

var pattern = @"\(.+?\)";
var match = Regex.Match(input, pattern, RegexOptions.RightToLeft);
if (match.Success)
{
    var result = input.Substring(0, match.Index);
    Console.WriteLine(result);
}
else
{
    Console.WriteLine(input);
}

Regex depending on numeric format

If you're always expecting the final parentheses to have numeric content, similar to your example values where (50) is getting removed, we can use a pattern that matches any numbers inside parentheses.

var patternNumeric = @"\(\d+\)";
var result = Regex.Replace(input, patternNumeric, "");
Console.WriteLine(result);

Upvotes: 2

Grant Winney
Grant Winney

Reputation: 66439

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());

Upvotes: 21

Felipe Oriani
Felipe Oriani

Reputation: 38598

try something a function this:

public static string ReplaceLastOccurrence(string source, string find, string replace)
{
    int place = source.LastIndexOf(find);
    return source.Remove(place, find.Length).Insert(place, replace);
}

It will remove the last occurrence of a string string and replace to another one, and use:

string result = ReplaceLastOccurrence(value, "(", string.Empty);

In this case, you find ( string inside the value string, and replace the ( to a string.Empty. It also could be used to replace to another information.

Upvotes: 0

Related Questions