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

前端 未结 7 1938
星月不相逢
星月不相逢 2020-12-09 14:07

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:

7条回答
  •  星月不相逢
    2020-12-09 14:52

    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.

提交回复
热议问题