Splitting a string into chunks of a certain size

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

    I've slightly build up on João's solution. What I've done differently is in my method you can actually specify whether you want to return the array with remaining characters or whether you want to truncate them if the end characters do not match your required chunk length, I think it's pretty flexible and the code is fairly straight forward:

    using System;
    using System.Linq;
    using System.Text.RegularExpressions;
    
    namespace SplitFunction
    {
        class Program
        {
            static void Main(string[] args)
            {
                string text = "hello, how are you doing today?";
                string[] chunks = SplitIntoChunks(text, 3,false);
                if (chunks != null)
                {
                    chunks.ToList().ForEach(e => Console.WriteLine(e));
                }
    
                Console.ReadKey();
            }
    
            private static string[] SplitIntoChunks(string text, int chunkSize, bool truncateRemaining)
            {
                string chunk = chunkSize.ToString(); 
                string pattern = truncateRemaining ? ".{" + chunk + "}" : ".{1," + chunk + "}";
    
                string[] chunks = null;
                if (chunkSize > 0 && !String.IsNullOrEmpty(text))
                    chunks = (from Match m in Regex.Matches(text,pattern)select m.Value).ToArray(); 
    
                return chunks;
            }     
        }
    }
    

提交回复
热议问题