我们说我有一个500字的字符串。我怎么能把这个字符串分成更小的单词。
例如,如果我想将其分成每个50个单词的块,我将留下10个50个单词的列表。如果最后一个块不能达到50个单词,则它应该是字符串中剩余的任何数量。
答案 0 :(得分:2)
这是一种简单的方法。
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);
}