In C#, perform "static" copy into a substring of a StringBuilder object
To build a sparsely populated fixed width开发者_开发知识库 record, I would like to copy a string field into a StringBuilder object, starting at a given position. A nice syntax for this would have been
StringBuilder sb = new StringBuilder(' ', 100);
string fieldValue = "12345";
int startPos = 16;
int endPos = startPos + fieldValue.Length - 1;
sb[startPos..endPos] = fieldValue; // no such syntax
I could obviously do this C style, one character at a time:
for (int ii = 0; ii++; ii < fieldValue.Length)
sb[startPos + ii] = fieldValue[ii];
But this seems way too cumbersome for c#, plus it uses a loop where the resulting machine code could more efficiently use a bulk copy, which can make a difference if the strings involved were long. Any ideas for a better way?
Your original algorithm can be supported in the following way
var builder = new StringBuilder(new string(' ', 100));
string toInsert = "HELLO WORLD";
int atIndex = 10;
builder.Remove(atIndex, toInsert.Length);
builder.Insert(atIndex, toInsert);
Debug.Assert(builder.Length == 100);
Debug.Assert(builder.ToString().IndexOf(toInsert) == 10);
You can write your own specialized string builder class that uses the efficient machinery of char[]
and string
underneath the hood, in particular String.CopyTo
:
public class FixedStringBuilder
{
char[] buffer;
public FixedStringBuilder(int length)
{
buffer = new string(' ', length).ToCharArray();
}
public FixedStringBuilder Replace(int index, string value)
{
value.CopyTo(0, buffer, index, value.Length);
return this;
}
public override string ToString()
{
return new string(buffer);
}
}
class Program
{
static void Main(string[] args)
{
FixedStringBuilder sb = new FixedStringBuilder(100);
string fieldValue = "12345";
int startPos = 16;
sb.Replace(startPos, fieldValue);
string buffer = sb.ToString();
}
}
The closest solution to your goal is to convert the source string in a char array, then substitute the cells. Any char array can be converted back to a string.
why are you pre-allocating memory in the string builder (it is only support performance).
i would append the known prefix, then the actual value and then the postfix to the string.
something like:
StringBuilder sb = new StringBuilder();
sb.Append(prefix).Append(value).Append(postfix);
精彩评论