How to split string preserving whole words?

前端 未结 10 2300
梦谈多话
梦谈多话 2020-11-30 09:18

I need to split long sentence into parts preserving whole words. Each part should have given maximum number of characters (including space, dots etc.). For example:

10条回答
  •  囚心锁ツ
    2020-11-30 10:01

    This works:

    int partLength = 35;
    string sentence = "Silver badges are awarded for longer term goals. Silver badges are uncommon.";
    List lines =
        sentence
            .Split(' ')
            .Aggregate(new [] { "" }.ToList(), (a, x) =>
            {
                var last = a[a.Count - 1];
                if ((last + " " + x).Length > partLength)
                {
                    a.Add(x);
                }
                else
                {
                    a[a.Count - 1] = (last + " " + x).Trim();
                }
                return a;
            });
    

    It gives me:

    Silver badges are awarded for 
    longer term goals. Silver badges 
    are uncommon. 
    

提交回复
热议问题