using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace XYY.Core.Standard.ExtendMethods { public static class StringExtendMethods { public static string[] ToArray(this string str, int maxLength) { string[] arr = str.Split(' ', '.', ','); if (arr.Any(x => x.Length >= maxLength)) { var a = arr.Where(x => x.Length > maxLength); throw new Exception($"拆分错误,尝试拆分地址{str}->{string.Join("+", a)}时,发现对于拆分长度{maxLength},无法拆分,请添加相应空格,逗号,句号处理"); } int page = ((str.Length + maxLength) - 1) / maxLength; List addressArr = new List(); int flag = 0; int t = arr.Count(); int i = 0; do { addressArr.Add(""); 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; arr[flag] = null; flag++; } } t = arr.Count() - flag; i++; } while (arr.Any(x => x != null)); if (arr.Any(x => x != null)) throw new Exception("地址拆分失败"); return addressArr.ToArray(); } public static string[] ToArray2(this string str, int maxLength) { string[] arr = str.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); 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; } } }