StringArrayExtensions.cs 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. namespace XYY.Common.Standard
  7. {
  8. public static class StringArrayExtensions
  9. {
  10. /// <summary>
  11. /// 把字符串按指定长度拆分为数组
  12. /// </summary>
  13. /// <param name="str"></param>
  14. /// <param name="maxLength"></param>
  15. /// <returns></returns>
  16. public static string[] ToArray(this string str, int maxLength)
  17. {
  18. string[] arr = str.Split(' ', '.');
  19. int page = ((str.Length + maxLength) - 1) / maxLength;
  20. string[] addressArr = new string[page];
  21. int flag = 0;
  22. int t = arr.Count();
  23. for (int i = 0; i < page; i++)
  24. {
  25. string temp = "";
  26. for (int j = 0; j < t; j++)
  27. {
  28. string splitor = j < t - 1 ? " " : string.Empty;//如果是最后一截,则不要加空格;
  29. if ((temp += arr[flag] + splitor).Length <= maxLength)
  30. {
  31. addressArr[i] += arr[flag] + splitor;
  32. flag++;
  33. }
  34. }
  35. t = arr.Count() - flag;
  36. }
  37. return addressArr;
  38. }
  39. }
  40. }