将字符串拆分为特定大小的块 [英] Splitting a string into chunks of a certain size
本文介绍了将字符串拆分为特定大小的块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有一个字符串:
string str = "1111222233334444";
如何将这个字符串分成一定大小的块?
How can I break this string into chunks of some size?
例如,将其分成 4 个大小将返回字符串:
e.g., breaking this into sizes of 4 would return strings:
"1111"
"2222"
"3333"
"4444"
推荐答案
static IEnumerable<string> Split(string str, int chunkSize)
{
return Enumerable.Range(0, str.Length / chunkSize)
.Select(i => str.Substring(i * chunkSize, chunkSize));
}
请注意,可能需要额外的代码来优雅地处理边缘情况(null
或空输入字符串,chunkSize == 0
,输入字符串长度不能被 chunkSize
等).最初的问题没有为这些边缘情况指定任何要求,在现实生活中,这些要求可能会有所不同,因此超出了本答案的范围.
Please note that additional code might be required to gracefully handle edge cases (null
or empty input string, chunkSize == 0
, input string length not divisible by chunkSize
, etc.). The original question doesn't specify any requirements for these edge cases and in real life the requirements might vary so they are out of scope of this answer.
这篇关于将字符串拆分为特定大小的块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文