-2

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.

Zach Johnson
  • 2,047
  • 6
  • 24
  • 40
  • 1
    You could try something like the answer specified [here](http://stackoverflow.com/a/4133475/2026606), perhaps. – Tyler Roper Oct 17 '16 at 23:25
  • What is wrong with the way you do it now and in what way you want to improve your current code? (You may have forgotten to put you current version in the post - make sure to [edit] it in). – Alexei Levenkov Oct 17 '16 at 23:29
  • I get it I didn't include any code. That's because this one stumped me. I actually do not no where to start. Is this site only for answering questions where code is already written? – Zach Johnson Oct 17 '16 at 23:34
  • It depends on what you consider a word. In this RegEx example https://regex101.com/r/qeTvyW/1 `Let's` is counted as 2 words, and `500` is counted as a word too. – Slai Oct 17 '16 at 23:50

1 Answers1

2

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;
do
{
    // 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)
{
    Console.WriteLine(item);
}
Andrew
  • 7,602
  • 2
  • 34
  • 42