Split string into fixed length blocks

suggest change

A 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;
    }
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents