c# - 使 Console.WriteLine() 换行而不是字母

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

我希望它自动看起来像这样,而不是在需要的地方手动放入 \n:

这可能吗?如果有,怎么做?

最佳答案

这是一个适用于制表符、换行符和其他空格的解决方案。

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);
    }
}

https://stackoverflow.com/questions/20534318/

相关文章:

c# - 将电话号码解析为其部分

c++ - 使用 boost::date_time 库以毫秒为单位格式化时间

c# - JSON 序列化输出具有 C# 转义格式

java - 通过 HotKey 在 Eclipse 中防止代码格式化

c# - 在 C# 中格式化大数

sql - 在 SQL 中显示带有加号 (+) 的肯定结果

css - Google Webfonts 在 Firefox、Chrome 和 Opera 中的呈

regex - 正则表达式中的 C# 字符串格式占位符

php - 定义跨平台money_format函数(Linux和Windows)

python - 使用 Python 在 OpenOffice/Microsoft Word 中格式