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