Splitting a string into chunks of a certain size

后端 未结 30 1634
时光说笑
时光说笑 2020-11-22 07:55

Suppose I had a string:

string str = \"1111222233334444\"; 

How can I break this string into chunks of some size?

e.g., breaking t

30条回答
  •  长发绾君心
    2020-11-22 08:10

    public static IEnumerable> SplitEvery(this IEnumerable values, int n)
    {
        var ls = values.Take(n);
        var rs = values.Skip(n);
        return ls.Any() ?
            Cons(ls, SplitEvery(rs, n)) : 
            Enumerable.Empty>();
    }
    
    public static IEnumerable Cons(T x, IEnumerable xs)
    {
        yield return x;
        foreach (var xi in xs)
            yield return xi;
    }
    

提交回复
热议问题