About Me

My photo
Fort Worth, TX, United States

Friday, July 6, 2007

Replace First Occurrence of a String in C#

I had a need to replace only the first occurrence of a substring within a string, and C# doesn't seem to have a way of doing this with the out-of-the-box String methods. So, I rolled my own:

public static string ReplaceFirstOccurrence(string original, string oldValue, string newValue)
{
    if (String.IsNullOrEmpty(original))
        return String.Empty;
    if (String.IsNullOrEmpty(oldValue))
        return original;
    if (String.IsNullOrEmpty(newValue))
        newValue = String.Empty;
    int loc = original.IndexOf(oldValue);
    return original.Remove(loc, oldValue.Length).Insert(loc, newValue);
}

If you're interested, here is the test case for this method:
[TestClass]
    public class ReplaceFirstOccurrenceTest
    {
        [TestMethod]
        public void TestReplaceFirstOccurrence()
        {
            Assert.AreEqual("", StringUtil.ReplaceFirstOccurrence(null, null, null));
            Assert.AreEqual("", StringUtil.ReplaceFirstOccurrence("", "", ""));
            Assert.AreEqual("Th is what is right.",
                StringUtil.ReplaceFirstOccurrence("This is what is right.", "is", null));
            Assert.AreEqual("Th is what is right.",
                StringUtil.ReplaceFirstOccurrence("This is what is right.", "is", ""));
            Assert.AreEqual("This is what is right.",
                StringUtil.ReplaceFirstOccurrence("This is what is right.", null, ""));
            Assert.AreEqual("This is what is right.",
                StringUtil.ReplaceFirstOccurrence("This is what is right.", "", "stuff"));
        }
    }

11 comments:

Lacuna said...

Thanks, this is exactly what I needed.

Pablo Benitez Barreto said...

if the string in not found you get and error. Other than it's great.

Unknown said...

All you have to do to fix the error is to add

if(loc == -1)
return original;

return original.Remove(loc, oldValue.Length).Insert(loc, newValue);

Joe Harker said...

Hey guys, thanks for the feedback! I've updated my ReplaceFirstOccurance() method (above) to handle a wide variety of bad input data. Also included are the test cases, if you're interested (you can add the test cases to your test project if you're doing test-driven development).

Anonymous said...

You spelled "occurance" wrong, it is "occurence"

Venkat said...

Very useful.

Anonymous said...

This one works too..

Regex originalValue = new Regex("original", RegexOptions.IgnoreCase);

return originalValue.Replace("originaloriginal", "duplicate", 1);

Anonymous said...

Thanks for the code

Ramya said...

This is very useful,but if the string that I want to replace is the last line in the file then it is not getting replaced.Any reason for that?

Anonymous said...

Anonymous said...
You spelled "occurance" wrong, it is "occurence"

^^O:

Joe Harker said...

Typo "occurrance" fixed.

@Ramya: I would have to see an example of your file and the code you're using to read through the file. This method just operates on strings, so it shouldn't matter where the strings come from or where they are located in a file, as long as the file is read in correctly.

Blog Archive