StringUtils.cs 3.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. using System;
  2. namespace XGame.Framework.Utils
  3. {
  4. public static class StringUtils
  5. {
  6. public static string Format(this string format, params object[] args)
  7. {
  8. if (string.IsNullOrEmpty(format))
  9. {
  10. return string.Empty;
  11. }
  12. if (args == null || args.Length <= 0)
  13. return format;
  14. else
  15. return string.Format(format, args);
  16. }
  17. /// <summary>
  18. /// 反斜杠替换为正斜杠
  19. /// </summary>
  20. /// <param name="path"></param>
  21. /// <returns></returns>
  22. public static string ReplaceSlash(this string path)
  23. {
  24. return path.Replace("\\", "/");
  25. }
  26. /// <summary>
  27. /// 字节数组转16进制字符串
  28. /// 每个字节转成两位的十六进制字符串
  29. /// </summary>
  30. /// <param name="bytes"></param>
  31. /// <returns></returns>
  32. public static string ToHexString(this byte[] bytes)
  33. {
  34. var length = bytes?.Length ?? 0;
  35. if (length == 0)
  36. return string.Empty;
  37. var sb = StringBuilderUtils.Acquire();
  38. for (int i = 0; i < length; i++)
  39. {
  40. sb.Append(bytes[i].ToString("X2"));
  41. }
  42. var result = sb.ToString();
  43. StringBuilderUtils.Release(sb);
  44. Log.Debug($"ToHexString Length:{length} result Length:{result.Length} val:{result}");
  45. return result;
  46. }
  47. /// <summary>
  48. /// 16进制字符串转字节数组
  49. /// 谨慎使用
  50. /// byte[].ToHexString()的逆向
  51. /// </summary>
  52. /// <param name="hexString"></param>
  53. /// <returns></returns>
  54. public static byte[] ToHexBytes(this string hexString)
  55. {
  56. //#if UNITY_EDITOR || DEBUG
  57. // hexString = CheakHexString(hexString);
  58. //#endif
  59. // hexString = hexString.Replace(" ", "");
  60. byte[] bytes = new byte[hexString.Length / 2];
  61. for (int i = 0; i < bytes.Length; i++)
  62. bytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
  63. return bytes;
  64. }
  65. ///// <summary>
  66. ///// 校验16进制字符串
  67. ///// </summary>
  68. ///// <param name="strBuffHex">16进制字符串</param>
  69. ///// <returns></returns>
  70. //private static string CheakHexString(string strBuffHex)
  71. //{
  72. // strBuffHex = strBuffHex.Trim(); //去除前后空字符
  73. // strBuffHex = strBuffHex.Replace(',', ' '); //去掉英文逗号
  74. // strBuffHex = strBuffHex.Replace(',', ' '); //去掉中文逗号
  75. // strBuffHex = strBuffHex.Replace("0x", ""); //去掉0x
  76. // strBuffHex = strBuffHex.Replace("0X", ""); //去掉0X
  77. // strBuffHex = Regex.Replace(Regex.Replace(strBuffHex, @"(?i)[^a-f\d\s]+", ""), "\\w{3,}", m => string.Join(" ", Regex.Split(m.Value, @"(?<=\G\w{2})(?!$)").Select(x => x.PadLeft(2, '0')).ToArray())).ToUpper();
  78. // return strBuffHex;
  79. //}
  80. }
  81. }