Splitting a string into chunks of a certain size

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

    static IEnumerable Split(string str, int chunkSize)
    {
       IEnumerable retVal = Enumerable.Range(0, str.Length / chunkSize)
            .Select(i => str.Substring(i * chunkSize, chunkSize))
    
       if (str.Length % chunkSize > 0)
            retVal = retVal.Append(str.Substring(str.Length / chunkSize * chunkSize, str.Length % chunkSize));
    
       return retVal;
    }
    

    It correctly handles input string length not divisible by chunkSize.

    Please note that additional code might be required to gracefully handle edge cases (null or empty input string, chunkSize == 0).

提交回复
热议问题