开发者

Problem in appending a string to a already filled string builder(at the beginning by using INSERT) and then converting that to string array(C#3.0)

I have a string builder like

StringBuilder sb = new StringBuilder("Value1");
sb.AppendLine("Value2");

Now I have a string say

string str = "value 0";

I did

sb.Insert(0,str);

and then

string[] strArr = sb.ToString().Trim().Replace("\r", string.Empty).Split('\n');

The result I am getting as (Array size of 2 where I should get 3)

[0] value 0 Value1

[1] value2

But the desired output being

[0] Value 0
[1] Value1
[2] Value2

Wh开发者_开发问答ere I am going wrong?

I am using C#3.0

Please help.. It 's urgent

Thanks


The method StringBuilder.Insert does not insert a new line automatically so you have to add one yourself:

string str = "value 0" + Environment.NewLine;


Actually, you would get an array of size one. You put "Value1" in the StringBuilder when you create it, then you add "Value2" and a line break, making the string "Value1Value2\r\n" (assuming the CR+LF line break for this example). Then you insert "Value 0" at the beginning, making the string "Value 0Value1Value2\r\n". Trimming the string removes the line break at the end, and splitting on a character that doesn't exist in the string gives you an array with only one item:

[0] Value 0Value1Value2

The Insert method doesn't add a line break like AppendLine does, so you have to add the line break manually:

StringBuilder sb = new StringBuilder();
sb.AppendLine("Value1");
sb.AppendLine("Value2");

string str = "value 0";
sb.Insert(0, str + Environment.NewLine);

Now you can trim and split the string:

string[] strArr =
  sb.ToString()
  .Trim()
  .Split(new string[]{ Environment.NewLine }, StringSplitOptions.None);


You are inserting Value 0 and which would result in the first line being Value0Value1

Insert will only insert a string at the specified position. It does work the same as AppendLine. As there is no carriage return your split won't work as you intended.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜