当文字超过一定长度时,将文字换行到下一行吗? [英] Wrap text to the next line when it exceeds a certain length?

查看:122
本文介绍了当文字超过一定长度时,将文字换行到下一行吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need to write different paragraphs of text within a certain area. For instance, I have drawn a box to the console that looks like this:

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

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

How would I write text within it, but wrap it to the next line if it gets too long?

推荐答案

在行长度之前在最后一个空格上分割?

Split on last space before your row length?

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);

UPDATE (上述解决方案在某些情况下会丢失最后一个字):

UPDATE (the solution above lost the last word in some cases):

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());

这篇关于当文字超过一定长度时,将文字换行到下一行吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆