Split String into smaller Strings by length variable

前端 未结 12 1927
谎友^
谎友^ 2020-12-01 07:19

I\'d like to break apart a String by a certain length variable.
It needs to bounds check so as not explode when the last section of string is not as long as or longer th

12条回答
  •  死守一世寂寞
    2020-12-01 08:07

    Here's what I'd do:

    public static IEnumerable 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.

提交回复
热议问题