Replace the last occurrence of a word in a string - C#
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;
string result = Source.Remove(place, Find.Length).Insert(place, Replace);
return result;
}
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.
Use string.LastIndexOf()
to find the index of the last occurrence of the string and then use substring to look for your solution.
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);