Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 685
Mariano Desanze Avatar asked Apr 05 '14 01:04

Mariano Desanze


People also ask

How do you indent multiple lines in notepad?

If you select multiple lines and hit “Tab”, Notepad++ will increase line indent. If you select multiple lines and hit “SHIFT+Tab”, Notepad++ will dicrease line indent.


1 Answers

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.

like image 185
WhoIsRich Avatar answered Sep 22 '22 06:09

WhoIsRich