gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 08:38:51 24 4
gpt4 key购买 nike

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

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

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

最佳答案

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

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com