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"
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"
I can't remember who gave me this, but it works great. I speed tested a number of ways to break Enumerable types into groups. The usage would just be like this...
The extention code would look like this...
This is based on @dove solution but implemented as an extension method.
Benefits:
Code
Usage
Unit tests removed for brevity (see previous revision)
and another approach:
Personally I prefer my solution :-)
It handles:
It is implemented as a extension method, and it calculates the number of chunks is going to generate beforehand. It checks the last chunk because in case the text length is not a multiple it needs to be shorter. Clean, short, easy to understand... and works!
It's not pretty and it's not fast, but it works, it's a one-liner and it's LINQy:
You can use morelinq by Jon Skeet. Use Batch like:
This will return 4 chunks for the string
"1111222233334444"
. If the string length is less than or equal to the chunk sizeBatch
will return the string as the only element ofIEnumerable<string>
For output:
and it will give: