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.
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.
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.
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 .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With