Zach Johnson Zach Johnson - 6 days ago 4x
C# Question

Best way to break up string into chunks of words?

Let's say I have a string with 500 words. How could I break this string up into smaller chunks of words.

For example if I wanted to break it up into chunks of 50 words each I would be left with a list of 10 chunks of 50 words. If the last chunk can not reach 50 words it should be whatever amount is left in the string.


Here's a simple way of doing it.

const int wordCount = 50;

string input = "Here comes your long text, use a smaller word count (like 4) for this example.";

// First get each word.
string[] words = input.Split(' ');
List<string> groups = new List<string>();
IEnumerable<string> remainingWords = words;
    // Then add them in groups of wordCount.
    groups.Add(string.Join(" ", remainingWords.Take(wordCount)));
    remainingWords = remainingWords.Skip(wordCount);
} while (remainingWords.Count() > 0);

// Finally, display them (only for a console application, of course).
foreach (var item in groups)