c#指定长度切割字符串,返回数组

     public List<string> subStringByCount(string text, int count)
        {
            int start_index = 0;//开始索引
            int end_index = count - 1;//结束索引

            double count_value = 1.0 * text.Length / count;
            double newCount = Math.Ceiling(count_value);//向上取整,只有有小数就取整,比如3.14,结果4

            List<string> list = new List<string>();
            for (int i = 0; i < newCount; i++)
            {
                //如果end_index大于字符长度,则添加剩下字符串
                if (end_index > text.Length - 1)
                {
                    list.Add(text.Substring(start_index));
                    break;
                }
                else
                {
                    list.Add(text.Substring(start_index, count));

                    start_index += count;
                    end_index += count;
                }
            }
            return list;
        }

效果:传入字符串“123456789”,个数传4

返回数组:["1234","5678","9"]

猜你喜欢

转载自www.cnblogs.com/codeDevotee/p/11886178.html