[英]Split a long string into an array of shorter strings
如何将一个约300(n)个单词的字符串拆分成一个包含30个字的n / 30个字符串的数组?
You can use Regex.Matches
: 您可以使用Regex.Matches
:
string[] bits = Regex.Matches(input, @"\w+(?:\W+\w+){0,29}")
.Cast<Match>()
.Select(match => match.Value)
.ToArray();
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类的Substring方法来获得所需的结果:
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.