Splitting a string into chunks of a certain size

后端 未结 30 2004
时光说笑
时光说笑 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

    This should be much faster and more efficient than using LINQ or other approaches used here.

    public static IEnumerable Splice(this string s, int spliceLength)
    {
        if (s == null)
            throw new ArgumentNullException("s");
        if (spliceLength < 1)
            throw new ArgumentOutOfRangeException("spliceLength");
    
        if (s.Length == 0)
            yield break;
        var start = 0;
        for (var end = spliceLength; end < s.Length; end += spliceLength)
        {
            yield return s.Substring(start, spliceLength);
            start = end;
        }
        yield return s.Substring(start);
    }
    

提交回复
热议问题