[英]Split a long string into an array of shorter strings
如何將一個約300(n)個單詞的字符串拆分成一個包含30個字的n / 30個字符串的數組?
您可以使用Regex.Matches
:
string[] bits = Regex.Matches(input, @"\w+(?:\W+\w+){0,29}")
.Cast<Match>()
.Select(match => match.Value)
.ToArray();
看到它在線工作: ideone
如果你有一個非常大或很小的字符可以成為字符串的一部分,那么正則表達式分割是有意義的。 或者,您可以使用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.