使Console.WriteLine()包装单词而不是字母

Jon*_*Jon 6 .net c# console formatting

使用Console.WriteLine(),它输出:

在此输入图像描述

我想让它看起来像这样,而不是手动放在\n任何需要的地方:

在此输入图像描述

这可能吗?如果是这样,怎么样?

Eni*_*ity 5

这将接受一个字符串并返回一个字符串列表,每个字符串不超过 80 个字符):

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;
});
Run Code Online (Sandbox Code Playgroud)

从这个开始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.";
Run Code Online (Sandbox Code Playgroud)

我得到这个结果:

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;
});
Run Code Online (Sandbox Code Playgroud)

  • @Dead.Rabit,为什么?你也可以只返回“lines”。 (2认同)
  • @SimonMᶜKenzie 你是对的,我收回它!lines 是使用“Aggregate”构建的,它返回一个 LINQ IEnumerable。返回线不仅是等效的,而且还稍微优化了一些。 (2认同)

roy*_*key 5

这是一个可以使用制表符,换行符和其他空格的解决方案.

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);
    }
}
Run Code Online (Sandbox Code Playgroud)


som*_*ody 0

这应该可行,尽管它可能可以进一步缩短:

    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]);
        }
    }
Run Code Online (Sandbox Code Playgroud)

可能很难理解,所以基本上它的作用是:

Trim()删除开头和结尾的空格。
Regex()多个空格替换为一个空格。
for循环从段落中获取第一个 (Console.WindowWidth - 1) 个字符并将其设置为新行。
`LastIndexOf()1 尝试查找行中的最后一个空格。如果没有,则该行保持原样。
该行将从段落中删除,并重复循环。

注意:正则表达式取自此处。注2:我不认为它取代了选项卡。