using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace XYY.Common.Standard
{
    public static class StringArrayExtensions
    {
        /// <summary>
        /// 把字符串按指定长度拆分为数组
        /// </summary>
        /// <param name="str"></param>
        /// <param name="maxLength"></param>
        /// <returns></returns>
        public static string[] ToArray(this string str, int maxLength)
        {
            string[] arr = str.Split(' ', '.');
            int page = ((str.Length + maxLength) - 1) / maxLength;
            string[] addressArr = new string[page];

            int flag = 0;
            int t = arr.Count();
            for (int i = 0; i < page; i++)
            {
                string temp = "";
                for (int j = 0; j < t; j++)
                {
                    string splitor = j < t - 1 ? " " : string.Empty;//如果是最后一截，则不要加空格;
                    if ((temp += arr[flag] + splitor).Length <= maxLength)
                    {
                        addressArr[i] += arr[flag] + splitor;
                        flag++;
                    }
                }
                t = arr.Count() - flag;
            }
            return addressArr;
        }
    }
}
