Working with long strings and found this problem. Any advice?
I have an instance where a string builder's Capacity is 1024 and Length is 99开发者_如何学Go2.
I am .Append() a string that has a .Length property of 1024.
After .Append() is called, the .ToString() method returns a long "\0\0\0" string.
What is going on? 0.o
If I create a new StringBuilder object and then append, I get what I expect. So the string "should" be ok right?
(I am clearing the stringbuilder out by doing the .Remove(0, LengthofSB) trick).
Any ideas?
It sounds to me like the original data in the StringBuilder
is "\0\0\0\0\0..." and that's what you're seeing - if you could see to the end of the string you'd see your real data.
This is exacerbated by various Windows controls truncating when they see "\0" as they treat it as a string termination character.
If you have a short but complete program which demonstrates the problem, we could confirm my suspicion.
As much i as i could make out from the question i tried running the following code below. It worked fine without the string "\0\0\0" mentioned by you as above. I have posted the code below. Do note since you have not provided how you were doing, i just think you were trying something like this. Also i am just creating two strings of 1024 with one string full of 'a' and other 'b' and joining them in the first stringbuilder object. it worked fine.
StringBuilder sb1 = new StringBuilder(1024);
for (int i = 0; i < 992; i++)
sb1.Append('a');
Console.WriteLine(sb1.ToString());
Console.WriteLine("{0}",sb1.Length);
StringBuilder sb2 = new StringBuilder();
for (int i = 0; i < 1024; i++)
sb2.Append('b');
Console.WriteLine(sb2.ToString());
Console.WriteLine("{0}",sb2.Length);
sb1.Append(sb2.ToString());
Console.WriteLine(sb1.ToString());
Console.WriteLine("{0}",sb1.Length);
精彩评论