Search code examples
c#stringindentation

Indent multiple lines of text


I need to indent multiple lines of text (in contrast to this question for a single line of text).

Let's say this is my input text:

First line
  Second line
Last line

What I need is this result:

    First line
      Second line
    Last line

Notice the indentation in each line.

This is what I have so far:

var textToIndent = @"First line
  Second line
Last line.";
var splittedText = textToIndent.Split(new string[] {Environment.NewLine}, StringSplitOptions.None);
var indentAmount = 4;
var indent = new string(' ', indentAmount);
var sb = new StringBuilder();
foreach (var line in splittedText) {
    sb.Append(indent);
    sb.AppendLine(line);
}
var result = sb.ToString();

Is there a safer/simpler way to do it?

My concern is in the split method, which might be tricky if text from Linux, Mac or Windows is transfered, and new lines might not get splitted correctly in the target machine.


Solution

  • Since you are indenting all the lines, how about doing something like:

    var result = indent + textToIndent.Replace("\n", "\n" + indent);
    

    Which should cover both Windows \r\n and Unix \n end of lines.