Web Design that taps into the haromny and vision of your dreams.

Replace First or Last Occurrence of a String with C#

By on in Coding

55 words, estimated reading time 1 minutes.

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;
}

Last updated on: Wednesday 21st June 2017

 

Comments

Have a question or suggestion? Please leave a comment to start the discussion.

Vibhu

Vibhu

Thanks for the function

Reply to Vibhu
Stephen P.

Stephen P.

Nicely done!
I will use this a LOT!

Reply to Stephen P.

 

Leave a Reply

Please keep in mind that all comments are moderated according to our privacy policy, and all links are nofollow. Do NOT use keywords in the name field. Let's have a personal and meaningful conversation.

Your email address will not be published.