当超过一定长度时将文本换行到下一行?

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)


Cor*_*lix 5

这是经过轻微测试并使用 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)

  • 啊有用!我自己使用递归添加了一个解决方案,但现在才看到这个解决方案。 (2认同)
  • 当输入字符串已包含换行符时,上面的代码不起作用 (2认同)
  • @TWT 您可以在转换之前用空格替换任何换行符。`v = v.Replace("\n"," ")` (2认同)