Splitting a string into chunks of a certain size

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

    In a combination of dove+Konstatin's answers...

    static IEnumerable WholeChunks(string str, int chunkSize) {
        for (int i = 0; i < str.Length; i += chunkSize) 
            yield return str.Substring(i, chunkSize);
    }
    

    This will work for all strings that can be split into a whole number of chunks, and will throw an exception otherwise.

    If you want to support strings of any length you could use the following code:

    static IEnumerable ChunksUpto(string str, int maxChunkSize) {
        for (int i = 0; i < str.Length; i += maxChunkSize) 
            yield return str.Substring(i, Math.Min(maxChunkSize, str.Length-i));
    }
    

    However, the the OP explicitly stated he does not need this; it's somewhat longer and harder to read, slightly slower. In the spirit of KISS and YAGNI, I'd go with the first option: it's probably the most efficient implementation possible, and it's very short, readable, and, importantly, throws an exception for nonconforming input.

提交回复
热议问题