Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

asp.net

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.

like image 877
4b0 Avatar asked Feb 12 '13 05:02

4b0


People also ask

How do you find the last occurrence of a character in a string in C?

The strrchr() function finds the last occurrence of c (converted to a character) in string . The ending null character is considered part of the string . The strrchr() function returns a pointer to the last occurrence of c in string . If the given character is not found, a NULL pointer is returned.

How do you find first occurrence of a string in a string c?

The strchr() function finds the first occurrence of a character in a string. The character c can be the null character (\0); the ending null character of string is included in the search.

How do you find the first and last occurrence of a character in a string?

The idea is to use charAt() method of String class to find the first and last character in a string. The charAt() method accepts a parameter as an index of the character to be returned. The first character in a string is present at index zero and the last character in a string is present at index length of string-1 .


2 Answers

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.
like image 128
Behroz Sikander Avatar answered Sep 27 '22 03:09

Behroz Sikander


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

like image 45
Montycarlo Avatar answered Sep 23 '22 03:09

Montycarlo