使用断字功能将字符串分割成固定长度的文本行

本文关键字:文本 分割 功能 字符串 | 更新日期: 2023-09-27 17:50:57

我需要接受一个输入字符串,并按照以下规则将其分成几行:

  1. 行必须小于等于80个字符。
  2. 行必须在空格上分开,不能将单词分成两行。

我已经试了三次了,但是我的代码实在是太糟糕了。

foreach (ChoiceClass c in q.ChoiceTextArray)
{
    int runningIndex = 0;
    int m = Math.Max(c.Description.Length - 1, 80);
    int numLines = (c.Description.Length / 80) + 1;
    while (numLines > 0)
    {
        int len = 80;
        if (numLines == 1)
        {
            len = c.Description.Length - runningIndex;
        }
        string tmp = string.Empty;
        if (numLines > 1)
        {
            tmp = c.Description.Substring(runningIndex, len);
        }
        else
        {
            if (runningIndex > c.Description.Length)
            {
                richTextBox2.Text += "'t" + tmp + eol;
                runningIndex += tmp.Length + 1;
                numLines--;
            }
            else
            {
                tmp = c.Description.Substring(runningIndex);
                richTextBox2.Text += "'t" + tmp + eol;
                runningIndex += tmp.Length + 1;
                numLines--;
            }
        }
    }
}

使用断字功能将字符串分割成固定长度的文本行

不确定代码是否比你的好得多…没有else语句

var text =
            @"this a asdf asdf asdf asdf asdf wdbwbwrthwrthw rthwrth wth wrt h wrn wrnbfb  wbwbwbb s  jkvjv j j o o  , , mfnfnsxuiua sdf asdfas dfasd f
asdf asd fasdf asdf asdf asdf asd fasdf asd fasdf asdf asdf asdf asdf asdf asd fasdf as
df asd fasdf asdf asdf asdf asdf asdf asdf asdf asdf asdf asdf asdf asdf asdf asdf ";
        var sb = new StringBuilder();
        var currentLine = String.Empty;
        var split = text.Split(' ');
        foreach (var s in split)
        {
            if (s.Length >= 80)
            {
                if (!String.IsNullOrEmpty(currentLine))
                {
                    sb.AppendLine(currentLine);
                    currentLine = "";
                }
                sb.AppendLine(s);
                continue;
            }
            if ((String.Format("{0} {1}", currentLine, s).Length > 80))
            {
                sb.AppendLine(currentLine);
                currentLine = "";
            }
            currentLine += s + " ";
        }
        if (!String.IsNullOrEmpty(currentLine))
        {
            sb.AppendLine(currentLine);
        }
        var final = sb.ToString();

我现在有一个工作的例子!

private void button1_Click(object sender, EventArgs e)
    {
       string somethingLongToPrint = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.";
       int i = 0;
       string tmp = string.Empty;
       string overrun = string.Empty;
       int len = somethingLongToPrint.Length - 1; // 0-based counting
       while( i < len)
       {
           if (overrun != string.Empty)
           {
               // to keep the length down to 80 and still account for overrun, i should subtract the length of overrun
               // If the number of characters left in "somethingLongToPrint" is less than 80, then then
               int numberOfCharactersRemaining = somethingLongToPrint.Length - i;
               if (numberOfCharactersRemaining > 80)
               {
                   tmp = overrun + somethingLongToPrint.Substring(i - overrun.Length, 80);
               }
               else
               {
                   tmp = overrun + somethingLongToPrint.Substring(somethingLongToPrint.Length - numberOfCharactersRemaining);
               }
           }
           else
           {
               tmp = somethingLongToPrint.Substring(i, ((80 - overrun.Length)));
           }
           overrun = print80CharacterLine(tmp);
           i += 80;
       }
    }
    // returns what was not printed
    private string print80CharacterLine(string src)
    {
        string eol = "'r'n";
        string whatIsLeft = string.Empty;
        int index = src.LastIndexOf(" ");
        string calculatedString = src.Substring(0, index);
        whatIsLeft = src.Substring((index+1));
        // print statement here
        // do the e.Graphics.DrawString(lines[linesPrinted], someFont, brush, x, y);
        textBox1.Text += calculatedString + eol;
        return whatIsLeft;

    }

将段落分割为固定长度的行,但不中断单词

    static IEnumerable<string> FunctionSplit(string stringToSplit, int maximumLineLength)
    {
        List<string> lines = new List<string>();
        string[] words = stringToSplit.Trim().Split(' ');
        string line = string.Empty;
        foreach (string word in words)
        {
            line = $"{line} {word}".Trim();
            if (line.Length >= maximumLineLength)
            {
                lines.Add(line);
                line = string.Empty;                       
            }
        }
        if (!String.IsNullOrWhiteSpace(line))
        {
            lines.Add(line);
        }            
        return lines;
    }