使Console.WriteLine()包装单词而不是字母 [英] Make Console.WriteLine() wrap words instead of letters

查看:105
本文介绍了使Console.WriteLine()包装单词而不是字母的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我希望它自动显示为这样,而不是手动放置在 \n 中的任何地方:

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

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

Is this possible? If so, how?

推荐答案

这应该可行,尽管它可以缩短更多时间:

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()删除开头和结尾的空格。

Regex()用一个空格替换多个空格。

for 循环采用第一个( Console.WindowWidth-1)段落中的字符并将其设置为新行。

`LastIndexOf()1试图找到该行的最后一个空格。如果没有,则按原样保留该行。

从段落中删除此行,然后重复循环。

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.

注意:正则表达式取自
注意2:我认为它不会取代标签页。

Note: The regex was taken from here. Note 2: I don't think it replaces tabs.

这篇关于使Console.WriteLine()包装单词而不是字母的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆