Split String into smaller Strings by length variable

前端 未结 12 1935
谎友^
谎友^ 2020-12-01 07:19

I\'d like to break apart a String by a certain length variable.
It needs to bounds check so as not explode when the last section of string is not as long as or longer th

12条回答
  •  清歌不尽
    2020-12-01 08:03

        private void button2_Click(object sender, EventArgs e)
        {
            string s = "AAABBBCCC";
            string[] a = SplitByLenght(s,3);
        }
    
        private string[] SplitByLenght(string s, int split)
        {
            //Like using List because I can just add to it 
            List list = new List();
    
                        // Integer Division
            int TimesThroughTheLoop = s.Length/split;
    
    
            for (int i = 0; i < TimesThroughTheLoop; i++)
            {
                list.Add(s.Substring(i * split, split));
    
            }
    
            // Pickup the end of the string
            if (TimesThroughTheLoop * split != s.Length)
            {
                list.Add(s.Substring(TimesThroughTheLoop * split));
            }
    
            return list.ToArray();
        }
    

提交回复
热议问题