4b0
4b0

Reputation: 22321

Replace the last occurrence of a word in a string - C#

I have a problem where I need to replace the last occurrence of a word in a string.

Situation: I am given a string which is in this format:

string filePath ="F:/jan11/MFrame/Templates/feb11";

I then replace TnaName like this:

filePath = filePath.Replace(TnaName, ""); // feb11 is TnaName

This works, but I have a problem when TnaName is the same as my folder name. When this happens I end up getting a string like this:

F:/feb11/MFrame/Templates/feb11

Now it has replaced both occurrences of TnaName with feb11. Is there a way that I can replace only the last occurrence of the word in my string?

Note: feb11 is TnaName which comes from another process - that's not a problem.

Upvotes: 116

Views: 96183

Answers (7)

Behroz Sikander
Behroz Sikander

Reputation: 4049

Here is the function to replace the last occurrence of a string

public static string ReplaceLastOccurrence(string source, string find, string replace)
{
    int place = source.LastIndexOf(find);
    
    if (place == -1)
       return source;
    
    return source.Remove(place, find.Length).Insert(place, replace);
}
  • source is the string on which you want to do the operation.
  • find is the string that you want to replace.
  • replace is the string that you want to replace it with.

Upvotes: 250

YMH
YMH

Reputation: 3133

The following function splits a string where the pattern (word to be replaced) last occurs.
Then it changes the pattern with the replacement string (in the second half of the string).
Finally, it concatenates both string halves back with each other again.

using System.Text.RegularExpressions;

public string ReplaceLastOccurance(string source, string pattern, string replacement)
{
   int splitStartIndex = source.LastIndexOf(pattern, StringComparison.OrdinalIgnoreCase);
   string firstHalf = source.Substring(0, splitStartIndex);
   string secondHalf = source.Substring(splitStartIndex, source.Length - splitStartIndex);
   secondHalf = Regex.Replace(secondHalf, pattern, replacement, RegexOptions.IgnoreCase);

   return firstHalf + secondHalf;
}

Upvotes: 0

MarcBalta
MarcBalta

Reputation: 131

The solution can be implemented even more simple with a single line:

 static string ReplaceLastOccurrence(string str, string toReplace, string replacement)
    {
        return Regex.Replace(str, $@"^(.*){Regex.Escape(toReplace)}(.*?)$", $"$1{Regex.Escape(replacement)}$2");
    }

Hereby we take advantage of the greediness of the regex asterisk operator. The function is used like this:

var s = "F:/feb11/MFrame/Templates/feb11";
var tnaName = "feb11";
var r = ReplaceLastOccurrence(s,tnaName, string.Empty);

Upvotes: 3

toddmo
toddmo

Reputation: 22476

I don't see why Regex can't be used:

public static string RegexReplace(this string source, string pattern, string replacement)
{
  return Regex.Replace(source,pattern, replacement);
}

public static string ReplaceEnd(this string source, string value, string replacement)
{
  return RegexReplace(source, $"{value}$", replacement);
}

public static string RemoveEnd(this string source, string value)
{
  return ReplaceEnd(source, value, string.Empty);
}

Usage:

string filePath ="F:/feb11/MFrame/Templates/feb11";
filePath = filePath.RemoveEnd("feb11"); // F:/feb11/MFrame/Templates/
filePath = filePath.ReplaceEnd("feb11","jan11"); // F:/feb11/MFrame/Templates/jan11

Upvotes: 4

Montycarlo
Montycarlo

Reputation: 735

Use string.LastIndexOf() to find the index of the last occurrence of the string and then use substring to look for your solution.

Upvotes: 12

IUnknown
IUnknown

Reputation: 22478

You can use a Path class from System.IO namepace:

string filePath = "F:/jan11/MFrame/Templates/feb11";

Console.WriteLine(System.IO.Path.GetDirectoryName(filePath));

Upvotes: 0

Moha Dehghan
Moha Dehghan

Reputation: 18472

You have to do the replace manually:

int i = filePath.LastIndexOf(TnaName);
if (i >= 0)
    filePath = filePath.Substring(0, i) + filePath.Substring(i + TnaName.Length);

Upvotes: 11

Related Questions