Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make Console.WriteLine() wrap words instead of letters

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?

like image 861
Jon Avatar asked Dec 12 '13 03:12

Jon


People also ask

How do you wrap text in C#?

You just call the WordWrap() extension method and pass it the column width you'd like. This will word wrap the text clamping to 10 characters in width.

What is use of console WriteLine () method?

Writes the text representation of the specified objects, followed by the current line terminator, to the standard output stream using the specified format information.

How do I print from console WriteLine?

By using: \n – It prints new line. By using: \x0A or \xA (ASCII literal of \n) – It prints new line. By using: Console. WriteLine() – It prints new line.

What language is console WriteLine?

A 'system' class is used first in the program to enable the use of classes and other data structures. Writeline is a built-in function in C sharp programming language that is used to print values on the console. Inside the main program, this function will play the role of displaying the values.


3 Answers

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);
    }
}
like image 179
roydukkey Avatar answered Sep 20 '22 13:09

roydukkey


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. 
like image 45
Enigmativity Avatar answered Sep 19 '22 13:09

Enigmativity


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.

like image 37
Alexandre Avatar answered Sep 20 '22 13:09

Alexandre