Learning never exhausts the mind
Home >  Coding > C# ASP.Net MVC > Replace First or Last Occurrence of a String with C#

Last Updated on by

This snippet provides two functions to replace only the first or the last occurrence of a string within a larger string. Using the Replace method will replace all occurrences found.
public static string ReplaceFirstOccurrence (string Source, string Find, string Replace)
{
    int Place = Source.IndexOf(Find);
    string result = Source.Remove(Place, Find.Length).Insert(Place, Replace);
    return result;
}

public static string ReplaceLastOccurrence(string Source, string Find, string Replace)
{
    int Place = Source.LastIndexOf(Find);
    string result = Source.Remove(Place, Find.Length).Insert(Place, Replace);
    return result;
}
2 thoughts on “Replace First or Last Occurrence of a String with C#
  • 10th April 2016 at 12:00 am

    Thanks for the function

    Reply
  • 14th May 2013 at 12:00 am

    Nicely done!
    I will use this a LOT!

    Reply

Leave a Reply

Fields marked with * are mandatory.

We respect your privacy, and will not make your email public. Hashed email address may be checked against Gravatar service to retrieve avatars. This site uses Akismet to reduce spam. Learn how your comment data is processed.