Replace First or Last Occurrence of a String in C#
October 15, 2010 0 CommentsThis 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
ReplaceFirstOccurance(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
ReplaceLastOccurance(string Source, string Find, string
Replace)
{
int Place = Source.LastIndexOf(Find);
string result = Source.Remove(Place, Find.Length).Insert(Place, Replace);
return result;
}
Subscribe