views:

258

answers:

3

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.

+3  A: 

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 If
Jon Seigel
That won't work simply if you don't know where in the string the first instance is.
Dan Puzey
@Dan: Updated, please read again.
Jon Seigel
A: 

If you know the location of the substring you want to replace (maybe by using IndexOf) you can use the overload of StringBuilder's replace.

public StringBuilder Replace(char oldChar,char newChar,int startIndex,int count);
NebuSoft
One of challenges with this approach is that StringBuilder doesn't have it's own IndexOf method.
epotter
+1  A: 

This 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");
}
Asad Butt
If I have to make several of these replacements in quick succession, is there a more efficient way to find the start stringToReplace than to create a new String object from the StringBuilder?
epotter