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

Replace First or Last Occurrence of a String with C#

Replace first or replace last occurrence of a string

Written 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
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

Your email address will not be published.





If you find something abusive or that does not comply with our terms or guidelines please flag it as inappropriate.

 

Copyright © 2001-2018 Tim Trott, all rights reserved. Web Design by Azulia Designs

This web page is licensed for your personal, private, non-commercial use only.

Disclaimer, Privacy & LegalSitemapContact Me