Maybe a basic question but let us say I have a string that is 2000 characters long, I need to split this string into max 512 character chunks each.
Is there a nice way,
Most of the answer may have the same flaw. Given an empty text they will yield nothing. We (I) expect at least to get back that empty string (same behaviour as a split on a char not in the string, which will give back one item : that given string)
so we should loop at least once all times (based on Jon's code) :
IEnumerable SplitIntoChunks (string text, int chunkSize)
{
int offset = 0;
do
{
int size = Math.Min (chunkSize, text.Length - offset);
yield return text.Substring (offset, size);
offset += size;
} while (offset < text.Length);
}
or using a for (Edited : after toying a little more with this, I found a better way to handle the case chunkSize greater than text) :
IEnumerable SplitIntoChunks (string text, int chunkSize)
{
if (text.Length <= chunkSize)
yield return text;
else
{
var chunkCount = text.Length / chunkSize;
var remainingSize = text.Length % chunkSize;
for (var offset = 0; offset < chunkCount; ++offset)
yield return text.Substring (offset * chunkSize, chunkSize);
// yield remaining text if any
if (remainingSize != 0)
yield return text.Substring (chunkCount * chunkSize, remainingSize);
}
}
That could also be used with the do/while loop ;)