Splitting a string into chunks of a certain size

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

    I took this to another level. Chucking is an easy one liner, but in my case I needed whole words as well. Figured I would post it, just in case someone else needs something similar.

    static IEnumerable Split(string orgString, int chunkSize, bool wholeWords = true)
    {
        if (wholeWords)
        {
            List result = new List();
            StringBuilder sb = new StringBuilder();
    
            if (orgString.Length > chunkSize)
            {
                string[] newSplit = orgString.Split(' ');
                foreach (string str in newSplit)
                {
                    if (sb.Length != 0)
                        sb.Append(" ");
    
                    if (sb.Length + str.Length > chunkSize)
                    {
                        result.Add(sb.ToString());
                        sb.Clear();
                    }
    
                    sb.Append(str);
                }
    
                result.Add(sb.ToString());
            }
            else
                result.Add(orgString);
    
            return result;
        }
        else
            return new List(Regex.Split(orgString, @"(?<=\G.{" + chunkSize + "})", RegexOptions.Singleline));
    }
    

提交回复
热议问题