StringTool.cs 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. //************************************************************************
  2. // https://github.com/yuzhengyang
  3. // author: yuzhengyang
  4. // date: 2017.3.29 - 2017.8.16
  5. // desc: 字符串工具类
  6. // Copyright (c) yuzhengyang. All rights reserved.
  7. //************************************************************************
  8. using System;
  9. using System.Collections.Generic;
  10. using System.Text;
  11. using System.Text.RegularExpressions;
  12. using Y.Utils.DataUtils.Collections;
  13. namespace Y.Utils.DataUtils.StringUtils
  14. {
  15. public sealed class StringTool
  16. {
  17. /// <summary>
  18. /// 判断字符串为null或为空格
  19. /// </summary>
  20. /// <param name="str"></param>
  21. /// <returns></returns>
  22. public static bool IsNullOrWhiteSpace(string str)
  23. {
  24. if (str == null)
  25. return true;
  26. if (str.Trim().Length == 0)
  27. return true;
  28. return false;
  29. }
  30. /// <summary>
  31. /// 分割字符串
  32. /// </summary>
  33. /// <param name="str"></param>
  34. /// <param name="separator"></param>
  35. /// <param name="result"></param>
  36. /// <returns></returns>
  37. public static int Split(string str, char separator, out string[] result)
  38. {
  39. if (!string.IsNullOrWhiteSpace(str))
  40. {
  41. string[] list = str.Split(separator);
  42. if (ListTool.HasElements(list))
  43. {
  44. result = list;
  45. return result.Length;
  46. }
  47. }
  48. result = null;
  49. return 0;
  50. }
  51. /// <summary>
  52. /// 字符串中字符出现次数
  53. /// </summary>
  54. /// <param name="s"></param>
  55. /// <param name="sub"></param>
  56. /// <returns></returns>
  57. public static int SubStringCount(string s, string sub)
  58. {
  59. if (s.Contains(sub))
  60. {
  61. string sReplaced = s.Replace(sub, "");
  62. return (s.Length - sReplaced.Length) / sub.Length;
  63. }
  64. return 0;
  65. }
  66. /// <summary>
  67. /// 根据通配符验证字符串
  68. /// </summary>
  69. /// <param name="s">字符串</param>
  70. /// <param name="pattern">通配符:%和_</param>
  71. /// <returns></returns>
  72. public static bool IsMatch(string s, string pattern)
  73. {
  74. try
  75. {
  76. //key = key.Replace("%", @"[\s\S]*").Replace("_", @"[\s\S]");
  77. pattern = pattern.Replace("%", ".*").Replace("_", ".");
  78. return Regex.IsMatch(s, pattern);
  79. }
  80. catch
  81. {
  82. return false;
  83. }
  84. }
  85. }
  86. }