How to split string preserving whole words?

前端 未结 10 2294
梦谈多话
梦谈多话 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 09:38

    I knew there had to be a nice LINQ-y way of doing this, so here it is for the fun of it:

    var input = "The quick brown fox jumps over the lazy dog.";
    var charCount = 0;
    var maxLineLength = 11;
    
    var lines = input.Split(' ', StringSplitOptions.RemoveEmptyEntries)
        .GroupBy(w => (charCount += w.Length + 1) / maxLineLength)
        .Select(g => string.Join(" ", g));
    
    // That's all :)
    
    foreach (var line in lines) {
        Console.WriteLine(line);
    }
    

    Obviously this code works only as long as the query is not parallel, since it depends on charCount to be incremented "in word order".

提交回复
热议问题