2

I want to add a white-space before the start of each line and except the first line of string. I am using

input:

abc
def
efg
hij

output:

abc
 def
 efg
 hij

My code:

string text = "abc\ndef\nhij";

string result = string.Join(Environment.NewLine, text
                      .Split(new string[] { Environment.NewLine }, StringSplitOptions.None)
                      .Select(line => " " + line));

TextArea1_trim_id.InnerText = result;
Johnny
  • 8,939
  • 2
  • 28
  • 33
Emmy
  • 145
  • 11

1 Answers1

3

The problem is with Environment.NewLine, if you do:

Console.WriteLine(Regex.Escape(Environment.NewLine))

you will notice it is \r\n or \r (Windows or Mac) but you expect only \n. Also, you could avoid the last Select by adding space during the Join.

string result = string.Join("\n ", text
    .Split(new string[] { "\n" }, StringSplitOptions.None));

n.b. Look also at this.

Johnny
  • 8,939
  • 2
  • 28
  • 33
  • thanks it is adding white-space before start of each line except very first line of string, but this code is adding a blank line between every two lines as well. What I want is It should only add space before start of each line and shouldn't add blank line after each line. I tried removing ''\n" `Split(new string[] { "" }, StringSplitOptions.None))`. but it is not working – Emmy Apr 01 '19 at 05:34
  • I've solved this problem. I've just replaced `StringSplitOptions.None` with `StringSplitOptions.RemoveEmptyEntries` and `Environment.NewLine` with `" "` now it is working fine. – Emmy Apr 01 '19 at 05:57