8

Using Console.WriteLine(), this it output:

enter image description here

I want it to look like this automatically, instead of manually putting in \n wherever needed:

enter image description here

Is this possible? If so, how?

7 Answers 7

5

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);
    }
}
1
  • Great solution, just one little change, the paragraph object must have a value and not null or empty. Otherwise the Replace() and the Split() will throw an exception... Adding a if(string.IsNullOrEmpty(paragraph)) return; will clear things up.
    – Adrian Hum
    May 1, 2018 at 2:24
4

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. 
3
  • Added foreach(var line in lines) yield return line; to the end when wrapping this in a function.
    – Dead.Rabit
    Apr 22, 2015 at 10:31
  • 2
    @Dead.Rabit, why? You may as well just return lines. Apr 25, 2015 at 1:12
  • 2
    @SimonMᶜKenzie you are right, I take it back! lines was built using Aggregate which returns a LINQ IEnumerable. Returning lines isn't just equivalent, it's slightly more optimised.
    – Dead.Rabit
    Apr 27, 2015 at 10:52
2

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.

1
  • It gives a StackOverflow exception. Occurs in line String line = buffer.ToString().Substring(0, buffer.Length - word.Length);
    – Jon
    Dec 12, 2013 at 4:14
0

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.

1
  • 1
    What happens when there are newlines? Why would you want to trim whitespace and replace multiple spaces? Multiple spaces would be useful in laying content out across multiple lines.
    – roydukkey
    Nov 3, 2015 at 20:30
0

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.

0
0

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 ]

-1

You should probably be able to utilize Console.WindowWidth with some look-ahead newline logic to make this happen.

1
  • Console.BufferWidth may be the better choice depending on what you're trying to achieve.
    – Dead.Rabit
    Apr 22, 2015 at 10:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.