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
Replacework on a substring of theStringBuildercontents, 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
ToStringon theStringBuilder.(Sorry for the VB, I have a VB project open.)