将字符串分割成一定大小的块(Splitting a string into chunks of a certain size)
假设我有一个字符串:
string str = "1111222233334444";我怎么能把这个字符串分成一些大小的块?
例如,将其分解为4的大小将返回字符串:
"1111" "2222" "3333" "4444"Suppose I had a string:
string str = "1111222233334444";How can I break this string into chunks of some size?
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等分)等等。 原始问题没有规定对这些边缘情况的任何要求,在现实生活中,要求可能会有所不同,因此它们超出了本答案的范围。
static IEnumerable<string> Split(string str, int chunkSize) { return Enumerable.Range(0, str.Length / chunkSize) .Select(i => str.Substring(i * chunkSize, 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.
更多推荐
发布评论