In my .NET program I allow a user to define “fields” which are values calculated by the business logic. These fields have a position and length, so that they can all be inserted into a single output string at a given index. I also allow a user to specify default content of this output string. If no field is defined to replace a given position, the default character is output instead
My question is, how can I do this efficiently? The StringBuilder class has an Insert(int index, string value) method, but this lengthens the output string each time rather than overwriting it. Am I going to have to set each char one at a time using the StringBuilder[int index] indexer, and is this inefficient? Since I am going to be doing this a lot of times I would like it to be as fast as possible.
Thanks.
Doing it one character at a time is likely your best bet. I say this because calling
InsertandRemoveon aStringBuilderresults in characters being shifted right/left, just as the analogous methods would in any mutable indexed collection such as aList<char>.That said, this is an excellent candidate for an extension method to make your life a bit easier.
Usage example:
Output: