在c#中按长度变量将字符串拆分为较小的单词

时间:2017-02-23 00:28:54

标签: c# string

您好我有一个包含25个单词和300个字符的字符串段落,我想将其设置为可包含40个字符的标签集。我正在尝试使用字符长度下面的代码。

public static List<string> _mSplitByLength(this string str, int maxLength)
{
    List<string> _a = new List<string>();
    for (int index = 0; index < str.Length; index += maxLength)
    {
        _a.Add(str.Substring(index, Math.Min(maxLength, str.Length - index)));
    }
    return _a;
}

使用上面的代码我可以将字符串拆分为40个字符,但问题是它也会拆分字。

假设我的字符串是"My school Name is stack over flow High school.",这是46个字符,因此我的代码就像这样

list 1 = "My school Name is stack over flow High s"
list 2 = "chool."

我的问题是如何根据单词拆分字符串。如果最后一个字没有提交,那么它应该转移到下一个列表。

我的目标是

list 1 = "My school Name is stack over flow High "
list 2 = "school."

1 个答案:

答案 0 :(得分:2)

试试这个:

string text = "My school Name is stack over flow High school.";
List<string> lines =
    text
        .Split(' ')
        .Aggregate(new [] { "" }.ToList(), (a, x) =>
        {
            var last = a[a.Count - 1];
            if ((last + " " + x).Length > 40)
            {
                a.Add(x);
            }
            else
            {
                a[a.Count - 1] = (last + " " + x).Trim();
            }
            return a;
        });

我明白了:

My school Name is stack over flow High 
school.