Splitting a string into chunks of a certain size

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

    This is based on @dove solution but implemented as an extension method.

    Benefits:

    • Extension method
    • Covers corner cases
    • Splits string with any chars: numbers, letters, other symbols

    Code

    public static class EnumerableEx
    {    
        public static IEnumerable SplitBy(this string str, int chunkLength)
        {
            if (String.IsNullOrEmpty(str)) throw new ArgumentException();
            if (chunkLength < 1) throw new ArgumentException();
    
            for (int i = 0; i < str.Length; i += chunkLength)
            {
                if (chunkLength + i > str.Length)
                    chunkLength = str.Length - i;
    
                yield return str.Substring(i, chunkLength);
            }
        }
    }
    

    Usage

    var result = "bobjoecat".SplitBy(3); // bob, joe, cat
    

    Unit tests removed for brevity (see previous revision)

提交回复
热议问题