将换行的文本拆分为数组

本文关键字:数组 拆分 文本 换行 | 更新日期: 2023-09-27 18:30:38

我想将字符串拆分为一个数组,在文本换行给定宽度的点

假设这是字符串。我希望文本宽度为 300 :

I want to split a string into an array at a point where the text wraps for a given width

并使用一个函数,如下所示:

Text.SplitAtWrap(300,Text)

这是我想要的输出:

(0) I want to split a string into an
(1) array at a point where the text
(2) wraps for a given width

编辑:我可能不得不考虑字体,所以可能不得不使用 Drawing.Graphics .

将换行的文本拆分为数组

这里有

一个答案(请赞扬谁应得的)

public List<string> GetSubstrings(string toSplit, int maxLength, Graphics graph, Font font)
{
     List<string> substrings = new List<string>();
     string[] words = toSplit.Split(" ".ToCharArray());
     string oneSub = "";
     foreach (string oneWord in words)
     {
        string temp = oneSub + oneWord + " ";
        if (graph.MeasureString( temp, font).Width > maxLength) 
        {
           substrings.Add(oneSub);
           oneSub = oneWord + " ";
        }
        else
           oneSub = temp;
     }
     substrings.Add(oneSub);
     return substrings;
}

基本上,输入字符串按其组成词划分,然后使用图形对象和参考字体测量每个单词。如果当前单词加上前面单词的长度小于所需的长度,则单词将重新连接在一起。否则,生成的字符串将添加到要返回给调用方的字符串列表中。