15

特定の領域内に異なる段落のテキストを書く必要があります。たとえば、次のようなボックスをコンソールに描画しました。

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

その中にテキストを書き込むにはどうすればよいでしょうか。ただし、長すぎる場合は次の行に折り返すでしょうか?

4

10 に答える 10

16

行の長さの前の最後のスペースで分割しますか?

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());
于 2012-05-10T20:22:40.523 に答える
3

私はJim H. のソリューションから始めて、この方法に行き着きました。唯一の問題は、テキストに制限を超える単語が含まれている場合です。しかし、うまく機能します。

public static List<string> GetWordGroups(string text, int limit)
{
    var words = text.Split(new string[] { " ", "\r\n", "\n" }, StringSplitOptions.None);

    List<string> wordList = new List<string>();

    string line = "";
    foreach (string word in words)
    {
        if (!string.IsNullOrWhiteSpace(word))
        {
            var newLine = string.Join(" ", line, word).Trim();
            if (newLine.Length >= limit)
            {
                wordList.Add(line);
                line = word;
            }
            else
            {
                line = newLine;
            }
        }
    }

    if (line.Length > 0)
        wordList.Add(line);

    return wordList;
}
于 2016-12-26T11:53:09.587 に答える
3

いくつかの特殊なケースをサポートするように Jim H のバージョンを修正しました。たとえば、文に空白文字が含まれていない場合。また、行の最後の位置にスペースがある場合に問題があることにも気付きました。その後、最後にスペースが追加され、1 文字が多すぎます。

誰かが興味を持っている場合に備えて、これが私のバージョンです。

public static List<string> WordWrap(string input, int maxCharacters)
{
    List<string> lines = new List<string>();

    if (!input.Contains(" "))
    {
        int start = 0;
        while (start < input.Length)
        {
            lines.Add(input.Substring(start, Math.Min(maxCharacters, input.Length - start)));
            start += maxCharacters;
        }
    }
    else
    {
        string[] words = input.Split(' ');

        string line = "";
        foreach (string word in words)
        {
            if ((line + word).Length > maxCharacters)
            {
                lines.Add(line.Trim());
                line = "";
            }

            line += string.Format("{0} ", word);
        }

        if (line.Length > 0)
        {
            lines.Add(line.Trim());
        }
    }

    return lines;
}
于 2014-05-21T20:41:59.803 に答える
0

私は少し遅れていることを知っていますが、再帰を使用して解決策を得ることができました。ここで提案された最もクリーンなソリューションの 1 つだと思います。

再帰関数:

public StringBuilder TextArea { get; set; } = new StringBuilder();

public void GenerateMultiLineTextArea(string value, int length)
{
    // first call - first length values -> append first length values, remove first length values from value, make second call
    // second call - second length values -> append second length values, remove first length values from value, make third call
    // third call - value length is less then length just append as it is

    if (value.Length <= length && value.Length != 0)
    {

        TextArea.Append($"|{value.PadRight(length)}" + "|");
    }
    else
    {
        TextArea.Append($"|{value.Substring(0, length).ToString()}".PadLeft(length) + "|\r\n");
        value = value.Substring(length, (value.Length) - (length));
        GenerateMultiLineTextArea(value, length);
    }
}

使用法:

string LongString = 
"This is a really long string that needs to break after it reaches a certain limit. " +
"This is a really long string that needs to break after it reaches a certain limit." + "This is a really long string that needs to break after it reaches a certain limit.";

GenerateMultiLineTextArea(LongString, 22);
Console.WriteLine("/----------------------\\");
Console.WriteLine(TextArea.ToString());
Console.WriteLine("\\----------------------/");

出力:

/----------------------\
|This is a really long |
|string that needs to b|
|reak after it reaches |
|a certain limit. This |
|is a really long strin|
|g that needs to break |
|after it reaches a cer|
|tain limit.This is a r|
|eally long string that|
| needs to break after |
|it reaches a certain l|
|imit.                 |
\----------------------/
于 2020-08-31T11:44:01.913 に答える