I've got a chunk of text in a StringBuilder object. I need to replace one substring with another. The StringBuilder Replace method can do this, but it replaces every instance of the substring and I only want to replace the first found instance. Is there a way to tell StringBuilder to only do one replace?
I'm sure I could code this up myself, I'm just wondering if there is a built in way to achieve this that I am currently missing.
Yes, but not directly. Two of the four overloads of Replace work on a substring of the StringBuilder contents, but you'll need to find the position of the first occurrence for that to work.
Here's the one you want:
http://msdn.microsoft.com/en-us/library/y1bxd041.aspx
Edit: Unfortunately, I don't see a way to find the first occurrence without calling ToString on the StringBuilder.
(Sorry for the VB, I have a VB project open.)
Dim orig As String = "abcdefgabcdefg"
Dim search As String = "d"
Dim replace As String = "ZZZ"
Dim sb As New StringBuilder(orig)
Dim firstOccurrence = sb.ToString().IndexOf(search)
If firstOccurrence > -1 Then
    sb.Replace(search, replace, firstOccurrence, search.Length)
End IfThis is different way of doing this, but works fine
        StringBuilder sb = new StringBuilder("OldStringOldWay");
        int index = sb.ToString().IndexOf("New");           
        sb.Remove(index, "Old".Length);
        sb.Insert(index, "New");
Another way could be using Extension Method
public static StringBuilder ReplaceOnce
             (this StringBuilder sb, string toReplace, string replaceWith)
     {
       int index = sb.ToString().IndexOf("New");
       sb.Remove(index, "Old".Length);
       sb.Insert(index, "New");
       return sb;
     }
And call ReplaceOnce as follows
static void Main(string[] args)
{
   StringBuilder sb = new StringBuilder("OldStringOldWay");
   sb.ReplaceOnce("Old", "New");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With