Here's what I'd do:
public static IEnumerable<string> EnumerateByLength(this string text, int length) {
int index = 0;
while (index < text.Length) {
int charCount = Math.Min(length, text.Length - index);
yield return text.Substring(index, charCount);
index += length;
}
}
This method would provide deferred execution (which doesn't really matter on an immutable class like string
, but it's worth noting).
Then if you wanted a method to populate an array for you, you could have:
public static string[] SplitByLength(this string text, int length) {
return text.EnumerateByLength(length).ToArray();
}
The reason I would go with the name EnumerateByLength
rather then SplitByLength
for the "core" method is that string.Split
returns a string[]
, so in my mind there's precedence for methods whose names start with Split
to return arrays.
That's just me, though.