Using Console.WriteLine()
, this it output:
I want it to look like this automatically, instead of manually putting in \n
wherever needed:
Is this possible? If so, how?
Here is a solution that will work with tabs, newlines, and other whitespace.
using System;
using System.Collections.Generic;
/// <summary>
/// Writes the specified data, followed by the current line terminator, to the standard output stream, while wrapping lines that would otherwise break words.
/// </summary>
/// <param name="paragraph">The value to write.</param>
/// <param name="tabSize">The value that indicates the column width of tab characters.</param>
public static void WriteLineWordWrap(string paragraph, int tabSize = 8)
{
string[] lines = paragraph
.Replace("\t", new String(' ', tabSize))
.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
for (int i = 0; i < lines.Length; i++) {
string process = lines[i];
List<String> wrapped = new List<string>();
while (process.Length > Console.WindowWidth) {
int wrapAt = process.LastIndexOf(' ', Math.Min(Console.WindowWidth - 1, process.Length));
if (wrapAt <= 0) break;
wrapped.Add(process.Substring(0, wrapAt));
process = process.Remove(0, wrapAt + 1);
}
foreach (string wrap in wrapped) {
Console.WriteLine(wrap);
}
Console.WriteLine(process);
}
}
This will take a string and return a list of strings each no longer than 80 characters):
var words = text.Split(' ');
var lines = words.Skip(1).Aggregate(words.Take(1).ToList(), (l, w) =>
{
if (l.Last().Length + w.Length >= 80)
l.Add(w);
else
l[l.Count - 1] += " " + w;
return l;
});
Starting with this text
:
var text = "Hundreds of South Australians will come out to cosplay when Oz Comic Con hits town this weekend with guest stars including the actor who played Freddy Krueger (A Nightmare on Elm Street) and others from shows such as Game of Thrones and Buffy the Vampire Slayer.";
I get this result:
Hundreds of South Australians will come out to cosplay when Oz Comic Con hits
town this weekend with guest stars including the actor who played Freddy Krueger
(A Nightmare on Elm Street) and others from shows such as Game of Thrones and
Buffy the Vampire Slayer.
Coded in a couple of minutes, it will actually break with words that have more than 80 characters and doesn't take into consideration the Console.WindowWidth
private static void EpicWriteLine(String text)
{
String[] words = text.Split(' ');
StringBuilder buffer = new StringBuilder();
foreach (String word in words)
{
buffer.Append(word);
if (buffer.Length >= 80)
{
String line = buffer.ToString().Substring(0, buffer.Length - word.Length);
Console.WriteLine(line);
buffer.Clear();
buffer.Append(word);
}
buffer.Append(" ");
}
Console.WriteLine(buffer.ToString());
}
It's also not very optimized on both CPU and Memory. I wouldn't use this in any serious context.
This should work, although it can probably be shortened some more:
public static void WordWrap(string paragraph)
{
paragraph = new Regex(@" {2,}").Replace(paragraph.Trim(), @" ");
var left = Console.CursorLeft; var top = Console.CursorTop; var lines = new List<string>();
for (var i = 0; paragraph.Length > 0; i++)
{
lines.Add(paragraph.Substring(0, Math.Min(Console.WindowWidth, paragraph.Length)));
var length = lines[i].LastIndexOf(" ", StringComparison.Ordinal);
if (length > 0) lines[i] = lines[i].Remove(length);
paragraph = paragraph.Substring(Math.Min(lines[i].Length + 1, paragraph.Length));
Console.SetCursorPosition(left, top + i); Console.WriteLine(lines[i]);
}
}
It may be hard to understand, so basically what this does:
Trim()
removes spaces at the start and the end.
The Regex()
replaces multiple spaces with one space.
The for
loop takes the first (Console.WindowWidth - 1) characters from the paragraph and sets it as a new line.
The `LastIndexOf()1 tries to find the last space in the line. If there isn't one, it leaves the line as it is.
This line is removed from the paragraph, and the loop repeats.
Note: The regex was taken from here. Note 2: I don't think it replaces tabs.
You can use CsConsoleFormat† to write strings to console with word wrap. It's actually the default text wrapping mode (but it can be changed to character wrap or no wrap).
var doc = new Document().AddChildren(
"2. I have bugtested this quite a bit however if something "
+ "goes wrong and the program crashes just restart it."
);
ConsoleRenderer.RenderDocument(doc);
You can also have an actual list with margin for numbers:
var docList = new Document().AddChildren(
new List().AddChildren(
new Div("I have not bugtested this enough so if something "
+ "goes wrong and the program crashes good luck with it."),
new Div("I have bugtested this quite a bit however if something "
+ "goes wrong and the program crashes just restart it.")
)
);
ConsoleRenderer.RenderDocument(docList);
Here's what it looks like:
† CsConsoleFormat was developed by me.
If you have a word (like a path) greater than screen width, you also needs word wrap.
using System;
using System.Text;
namespace Colorify.Terminal
{
public static class Wrapper
{
static int _screenWidth { get; set; }
public static void Text(string text)
{
StringBuilder line = new StringBuilder();
string[] words = text.Split(' ');
_screenWidth = (Console.WindowWidth - 3);
foreach (var item in words)
{
Line(ref line, item);
Item(ref line, item);
}
if (!String.IsNullOrEmpty(line.ToString().Trim()))
{
Out.WriteLine($"{line.ToString().TrimEnd()}");
}
}
static void Line(ref StringBuilder line, string item)
{
if (
((line.Length + item.Length) >= _screenWidth) ||
(line.ToString().Contains(Environment.NewLine))
)
{
Out.WriteLine($"{line.ToString().TrimEnd()}");
line.Clear();
}
}
static void Item(ref StringBuilder line, string item)
{
if (item.Length >= _screenWidth)
{
if (line.Length > 0)
{
Out.WriteLine($" {line.ToString().TrimEnd()}");
line.Clear();
}
int chunkSize = item.Length - _screenWidth;
string chunk = item.Substring(0, _screenWidth);
line.Append($"{chunk} ");
Line(ref line, item);
item = item.Substring(_screenWidth, chunkSize);
Item(ref line, item);
}
else
{
line.Append($"{item} ");
}
}
}
}
Its already implemented on Colorify - C# NETCore Console Library with Text Format: colors, alignment and lot more [ for Win, Mac & Linux ]
You should probably be able to utilize Console.WindowWidth with some look-ahead newline logic to make this happen.