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

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 ?
 
J

Jon Skeet [C# MVP]

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

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top