Re: Looking For An Example Of Replacing Only One Occurrence In A String
From: Jon Skeet [C# MVP] (skeet_at_pobox.com)
Date: 02/17/04
- Next message: Tommy: "Re: Execute function from within a class"
- Previous message: Robert Johnson: "Looking For An Example Of Replacing Only One Occurrence In A String"
- In reply to: Robert Johnson: "Looking For An Example Of Replacing Only One Occurrence In A String"
- Messages sorted by: [ date ] [ thread ]
Date: Tue, 17 Feb 2004 17:14:53 -0000
Robert Johnson <Robert.Johnson3@Anheuser-Busch.com> wrote:
> 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);
}
-- Jon Skeet - <skeet@pobox.com> http://www.pobox.com/~skeet If replying to the group, please do not mail me too
- Next message: Tommy: "Re: Execute function from within a class"
- Previous message: Robert Johnson: "Looking For An Example Of Replacing Only One Occurrence In A String"
- In reply to: Robert Johnson: "Looking For An Example Of Replacing Only One Occurrence In A String"
- Messages sorted by: [ date ] [ thread ]
Relevant Pages
|