Split string into fixed length blocks
suggest changeA string cannot be split on an arbitrary char boundary. A char may be a combining character or one half of a surrogate pair. The length here is a number of graphemes (text elements), not UTF-16 code units. StringInfo is in System.Globalization.
public static IEnumerable<string> Split(this string value, int desiredLength)
{
var characters = StringInfo.GetTextElementEnumerator(value);
while (characters.MoveNext())
yield return String.Concat(Take(characters, desiredLength));
}
private static IEnumerable<string> Take(TextElementEnumerator enumerator, int count)
{
for (int i = 0; i < count; ++i)
{
yield return (string)enumerator.Current;
if (i + 1 == count || !enumerator.MoveNext())
yield break;
}
}
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents