Splitting a string into chunks of a certain size

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

    Why not loops? Here's something that would do it quite well:

            string str = "111122223333444455";
            int chunkSize = 4;
            int stringLength = str.Length;
            for (int i = 0; i < stringLength ; i += chunkSize)
            {
                if (i + chunkSize > stringLength) chunkSize = stringLength  - i;
                Console.WriteLine(str.Substring(i, chunkSize));
    
            }
            Console.ReadLine();
    

    I don't know how you'd deal with case where the string is not factor of 4, but not saying you're idea is not possible, just wondering the motivation for it if a simple for loop does it very well? Obviously the above could be cleaned and even put in as an extension method.

    Or as mentioned in comments, you know it's /4 then

    str = "1111222233334444";
    for (int i = 0; i < stringLength; i += chunkSize) 
      {Console.WriteLine(str.Substring(i, chunkSize));} 
    

提交回复
热议问题