0
0

StringHelper.cs 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. using System;
  2. using System.Text;
  3. using System.Text.RegularExpressions;
  4. namespace Admin.Core.Common.Helpers
  5. {
  6. /// <summary>
  7. /// 字符串帮助类
  8. /// </summary>
  9. public class StringHelper
  10. {
  11. private static readonly char[] _constant = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' };
  12. /// <summary>
  13. /// 生成随机字符串,默认32位
  14. /// </summary>
  15. /// <param name="length">随机数长度</param>
  16. /// <returns></returns>
  17. public static string GenerateRandom(int length = 32)
  18. {
  19. var newRandom = new StringBuilder();
  20. var rd = new Random();
  21. for (int i = 0; i < length; i++)
  22. {
  23. newRandom.Append(_constant[rd.Next(_constant.Length)]);
  24. }
  25. return newRandom.ToString();
  26. }
  27. /// <summary>
  28. /// 生成随机字符串,只包含数字
  29. /// </summary>
  30. /// <param name="length"></param>
  31. /// <returns></returns>
  32. public static string GenerateRandomNumber(int length = 6)
  33. {
  34. var newRandom = new StringBuilder();
  35. var rd = new Random();
  36. for (int i = 0; i < length; i++)
  37. {
  38. newRandom.Append(_constant[rd.Next(10)]);
  39. }
  40. return newRandom.ToString();
  41. }
  42. public static string Format(string str, object obj)
  43. {
  44. if (str.IsNull())
  45. {
  46. return str;
  47. }
  48. string s = str;
  49. if (obj.GetType().Name == "JObject")
  50. {
  51. foreach (var item in (Newtonsoft.Json.Linq.JObject)obj)
  52. {
  53. var k = item.Key.ToString();
  54. var v = item.Value.ToString();
  55. s = Regex.Replace(s, "\\{" + k + "\\}", v, RegexOptions.IgnoreCase);
  56. }
  57. }
  58. else
  59. {
  60. foreach (System.Reflection.PropertyInfo p in obj.GetType().GetProperties())
  61. {
  62. var xx = p.Name;
  63. var yy = p.GetValue(obj).ToString();
  64. s = Regex.Replace(s, "\\{" + xx + "\\}", yy, RegexOptions.IgnoreCase);
  65. }
  66. }
  67. return s;
  68. }
  69. }
  70. }