Looking For An Example Of Replacing Only One Occurrence In A String

  • Thread starter Thread starter Robert Johnson
  • Start date Start date
R

Robert Johnson

Does anyone have an example of replacing only one occurrence of a
substring in a string. I have tried replace, but it replaces all
occurrences of the new string in the string. I only want to replace
the specified occurrence in the string (i.e substring(37, 10) - phone
number) with a new phone number. Am I making any sense here or do I
need to provide more detail ?
 
Robert Johnson said:
Does anyone have an example of replacing only one occurrence of a
substring in a string. I have tried replace, but it replaces all
occurrences of the new string in the string. I only want to replace
the specified occurrence in the string (i.e substring(37, 10) - phone
number) with a new phone number. Am I making any sense here or do I
need to provide more detail ?

This should do the trick:

public static string ReplaceFirst (string whole, string original,
string replacement)
{
int index = whole.IndexOf(original);
if (index==-1)
{
return whole;
}

return whole.Substring(0, index)+
replacement+
whole.Substring(index+original.Length);
}
 
Back
Top