Rya*_* S. 11 c# console-application
我需要在某个区域内写出不同的文本段落.例如,我在控制台上绘制了一个如下所示的框:
/----------------------\
| |
| |
| |
| |
\----------------------/
Run Code Online (Sandbox Code Playgroud)
我如何在其中写入文本,但如果它太长则将其包装到下一行?
Jim*_*m H 11
在行长之前的最后一个空格上拆分?
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);
Run Code Online (Sandbox Code Playgroud)
更新(上面的解决方案在某些情况下丢失了最后一个字):
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());
Run Code Online (Sandbox Code Playgroud)
这是经过轻微测试并使用 LastIndexOf 来加快速度的一个(猜测):
private static string Wrap(string v, int size)
{
v = v.TrimStart();
if (v.Length <= size) return v;
var nextspace = v.LastIndexOf(' ', size);
if (-1 == nextspace) nextspace = Math.Min(v.Length, size);
return v.Substring(0, nextspace) + ((nextspace >= v.Length) ?
"" : "\n" + Wrap(v.Substring(nextspace), size));
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
18884 次 |
| 最近记录: |