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

Tech-Archive recommends: Fix windows errors by optimizing your registry

From: Jon Skeet [C# MVP] (skeet_at_pobox.com)
Date: 02/17/04


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


Relevant Pages

  • Re: Find & Replace Whole Words
    ... I do not think Excel has the functionality you require built-in. ... string or a whole string, NOT a whole word within a string. ... I am sure there are ways do this in VBA, but I cannot think of anything ... and the same for the replacing string. ...
    (microsoft.public.excel.programming)
  • Re: Computability and logic
    ... as regards a mathematical formulation of a substring ... substring in a string with another substring? ... result of substituting a term for a variable in a formula'. ... As I recall, he doesn't get into replacing term for term, ...
    (sci.logic)
  • Re: Why COBOL is losing the POWER struggle
    ... UNSTRING, INSPECT/REPLACING followed by STRING would do it. ... Perhaps a more carefulreading would reveal that what I said was "my BUFFER ... len 4 with an eight-byte string without some sort of compression? ... If INSPECT ...REPLACING could do that it would be more powerful than it is. ...
    (comp.lang.cobol)
  • Re: String Parsing
    ... anyone give me an example of how I might parse a string, replacing certain instances of words with other words? ... For example, replacing "Ave." ... expresison" in Perl lingo (though I wouln't be surprised if anyone came up with a regular expression matching a valid sentence in modern English ...
    (comp.lang.perl.misc)
  • Re: [PHP] Re: $_GET strings seperation
    ... > have a single cID variable in the GET string? ... for you to insert a replacement property in a query string. ... foreach { ... replacing the current values that need replacing while retaining all other ...
    (php.general)