Suppose I had a string:
string str = \"1111222233334444\";
How can I break this string into chunks of some size?
e.g., breaking t
This is based on @dove solution but implemented as an extension method.
Benefits:
Code
public static class EnumerableEx
{
public static IEnumerable SplitBy(this string str, int chunkLength)
{
if (String.IsNullOrEmpty(str)) throw new ArgumentException();
if (chunkLength < 1) throw new ArgumentException();
for (int i = 0; i < str.Length; i += chunkLength)
{
if (chunkLength + i > str.Length)
chunkLength = str.Length - i;
yield return str.Substring(i, chunkLength);
}
}
}
Usage
var result = "bobjoecat".SplitBy(3); // bob, joe, cat
Unit tests removed for brevity (see previous revision)