我需要在某个区域内写不同的文本段落。例如,我在控制台上绘制了一个框,如下所示:
/----------------------\
| |
| |
| |
| |
\----------------------/
我如何在其中写入文本,但如果太长则换行到下一行?
最佳答案
拆分行长度之前的最后一个空格?
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/