Reputation: 81
I am writing out a large string (around 100 lines) to a text file, and would like the entire block of text tabbed.
WriteToOutput("\t" + strErrorOutput);
The line I am using above only tabs the first line of the text. How can I indent/tab the entire string?
Upvotes: 0
Views: 712
Reputation: 783
If you're here looking for a way to word-wrap a string to a certain width, and have each line indented (as I was), here's a solution as an extension method. Roughly based on the answer above, but uses regular expressions to split the original text into word and spaces pairs, then rejoins them, adding line breaks and indentation as needed. (Does not sanity check inputs, so you'll need to add that if needed)
public string ToBlock(this string text, int lineLength, string indent="")
{
var r = new Regex("([^ ]+)?([ ]+)?");
var matches = r.Match(text);
if (!matches.Success)
{
return text;
}
string output = indent;
int currentLineLength = indent.Length;
while (matches.Success)
{
var groups = matches.Groups;
var nextLength = groups[0].Length;
if (currentLineLength + nextLength <= lineLength)
{
output += groups[0];
currentLineLength += groups[0].Length;
}
else
{
if (currentLineLength + groups[1].Length > lineLength)
{
output += "\n" + indent + groups[0];
currentLineLength = indent.Length + groups[0].Length;
}
else
{
output += groups[1] + "\n" + indent;
currentLineLength = indent.Length;
}
}
matches = matches.NextMatch();
}
return output;
}
Upvotes: 0
Reputation: 4594
To do so you would have to have a limited line length (ie <100 characters) at which point this issue becomes easy.
public string ConvertToBlock(string text, int lineLength)
{
string output = "\t";
int currentLineLength = 0;
for (int index = 0; index < text.Length; index++)
{
if (currentLineLength < lineLength)
{
output += text[index];
currentLineLength++;
}
else
{
if (index != text.Length - 1)
{
if (text[index + 1] != ' ')
{
int reverse = 0;
while (text[index - reverse] != ' ')
{
output.Remove(index - reverse - 1, 1);
reverse++;
}
index -= reverse;
output += "\n\t";
currentLineLength = 0;
}
}
}
}
return output;
}
This will convert any text into a block of text that is broken up into lines of length lineLength
and that all start with a tab and end with a newline.
Upvotes: 1
Reputation: 32797
File.WriteAllLines(FILEPATH,input.Split(new string[] {"\n","\r"}, StringSplitOptions.None)
.Select(x=>"\t"+x));
Upvotes: 1
Reputation: 12524
You could make a copy of your string for output that replaces CRLF with CRLF + TAB. And the write that string to output (still prefixed with the initial TAB).
strErrorOutput = strErrorOutput.Replace("\r\n", "\r\n\t");
WriteToOutput("\t" + strErrorOutput);
Upvotes: 0
Reputation: 77304
Replace all linebreaks by linebreak followed by a tab:
WriteToOutput("\t" + strErrorOutput.Replace("\n", "\n\t"));
Upvotes: 1