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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With