How can I split a string of around 300 (n) words开发者_运维百科 into an array of n/30 strings of 30 words?
You can use Regex.Matches
:
string[] bits = Regex.Matches(input, @"\w+(?:\W+\w+){0,29}")
.Cast<Match>()
.Select(match => match.Value)
.ToArray();
See it working online: ideone
A Regex split would make sense if you have a very large or a very small of characters that can be a part of your string. Alternatively, you can use the Substring method of the String class to get the desired result:
string input = "abcdefghijklmnopqrstuvwxyz";
const int INTERVAL = 5;
List<string> lst = new List<string>();
int i = 0;
while (i < input.Length)
{
string sub = input.Substring(i, i + INTERVAL < input.Length ? INTERVAL : input.Length - i);
Console.WriteLine(sub);
lst.Add(sub);
i += INTERVAL;
}
精彩评论