StringExtendMethods.cs 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. namespace XYY.Core.Standard.ExtendMethods
  7. {
  8. public static class StringExtendMethods
  9. {
  10. public static string[] ToArray(this string str, int maxLength)
  11. {
  12. string[] arr = str.Split(' ', '.', ',');
  13. if (arr.Any(x => x.Length >= maxLength))
  14. {
  15. var a = arr.Where(x => x.Length > maxLength);
  16. throw new Exception($"拆分错误,尝试拆分地址{str}->{string.Join("+", a)}时,发现对于拆分长度{maxLength},无法拆分,请添加相应空格,逗号,句号处理");
  17. }
  18. int page = ((str.Length + maxLength) - 1) / maxLength;
  19. List<string> addressArr = new List<string>();
  20. int flag = 0;
  21. int t = arr.Count(); int i = 0;
  22. do
  23. {
  24. addressArr.Add("");
  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. arr[flag] = null;
  33. flag++;
  34. }
  35. }
  36. t = arr.Count() - flag;
  37. i++;
  38. }
  39. while (arr.Any(x => x != null));
  40. if (arr.Any(x => x != null))
  41. throw new Exception("地址拆分失败");
  42. return addressArr.ToArray();
  43. }
  44. public static string[] ToArray2(this string str, int maxLength)
  45. {
  46. string[] arr = str.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
  47. int page = ((str.Length + maxLength) - 1) / maxLength;
  48. string[] addressArr = new string[page];
  49. int flag = 0;
  50. int t = arr.Count();
  51. for (int i = 0; i < page; i++)
  52. {
  53. string temp = "";
  54. for (int j = 0; j < t; j++)
  55. {
  56. string splitor = j < t - 1 ? " " : String.Empty;//如果是最后一截,则不要加空格;
  57. if ((temp += arr[flag] + splitor).Length <= maxLength)
  58. {
  59. addressArr[i] += arr[flag] + splitor;
  60. flag++;
  61. }
  62. }
  63. t = arr.Count() - flag;
  64. }
  65. return addressArr;
  66. }
  67. }
  68. }