c# - 当文本超过一定长度时换行到下一行?

标签 c# console-application

我需要在某个区域内写不同的文本段落。例如,我在控制台上绘制了一个框,如下所示:

/----------------------\
|                      |
|                      |
|                      |
|                      |
\----------------------/

我如何在其中写入文本,但如果太长则换行到下一行?

最佳答案

拆分行长度之前的最后一个空格?

int myLimit = 10;
string sentence = "this is a long sentence that needs splitting to fit";
string[] words = sentence.Split(new char[] { ' ' });
IList<string> sentenceParts = new List<string>();
sentenceParts.Add(string.Empty);

int partCounter = 0;

foreach (string word in words)
{
    if ((sentenceParts[partCounter] + word).Length > myLimit)
    {
        partCounter++;
        sentenceParts.Add(string.Empty);
    }

    sentenceParts[partCounter] += word + " ";
}

foreach (string x in sentenceParts)
    Console.WriteLine(x);

更新(上面的解决方案在某些情况下丢失了最后一句话):

int myLimit = 10;
string sentence = "this is a long sentence that needs splitting to fit";
string[] words = sentence.Split(' ');

StringBuilder newSentence = new StringBuilder();


string line = "";
foreach (string word in words)
{
    if ((line + word).Length > myLimit)
    {
        newSentence.AppendLine(line);
        line = "";
    }

    line += string.Format("{0} ", word);
}

if (line.Length > 0)
    newSentence.AppendLine(line);

Console.WriteLine(newSentence.ToString());

关于c# - 当文本超过一定长度时换行到下一行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10541124/

相关文章:

c# - C# 中的简单控制台游戏出现巨大闪烁

c# - 缺少 Visual Studio 2017 控制台项目模板

c# - 如何检查字符串是否包含带通配符的子字符串?像 abc*xyz

c# - Selenium Chrome 60 Headless 处理基于 HTTPS 的基本身份验证 SAML 对话框

javascript - 为什么我无法使用 JSON 数据?

c# - 无法从传输连接读取数据 : The connection was closed error in console application

c# - 打开进程启动命令提示符后如何在 C# 中编写 ipconfig

c# - 如何创建 WinForm 应用程序中已存在的面板列表 (C#)

c# - 安全地比较本地和通用日期时间

debugging - 在 GoLand 的控制台中运行 termbox-go app