StringHelper.cs 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Globalization;
  4. using System.Text;
  5. namespace ET
  6. {
  7. public static class StringHelper
  8. {
  9. public static IEnumerable<byte> ToBytes(this string str)
  10. {
  11. byte[] byteArray = Encoding.Default.GetBytes(str);
  12. return byteArray;
  13. }
  14. public static byte[] ToByteArray(this string str)
  15. {
  16. byte[] byteArray = Encoding.Default.GetBytes(str);
  17. return byteArray;
  18. }
  19. public static byte[] ToUtf8(this string str)
  20. {
  21. byte[] byteArray = Encoding.UTF8.GetBytes(str);
  22. return byteArray;
  23. }
  24. public static byte[] HexToBytes(this string hexString)
  25. {
  26. if (hexString.Length % 2 != 0)
  27. {
  28. throw new ArgumentException(String.Format(CultureInfo.InvariantCulture, "The binary key cannot have an odd number of digits: {0}", hexString));
  29. }
  30. var hexAsBytes = new byte[hexString.Length / 2];
  31. for (int index = 0; index < hexAsBytes.Length; index++)
  32. {
  33. string byteValue = "";
  34. byteValue += hexString[index * 2];
  35. byteValue += hexString[index * 2 + 1];
  36. hexAsBytes[index] = byte.Parse(byteValue, NumberStyles.HexNumber, CultureInfo.InvariantCulture);
  37. }
  38. return hexAsBytes;
  39. }
  40. public static string Fmt(this string text, params object[] args)
  41. {
  42. return string.Format(text, args);
  43. }
  44. public static string ListToString<T>(this List<T> list)
  45. {
  46. StringBuilder sb = new StringBuilder();
  47. foreach (T t in list)
  48. {
  49. sb.Append(t);
  50. sb.Append(",");
  51. }
  52. return sb.ToString();
  53. }
  54. public static string ArrayToString<T>(this T[] args)
  55. {
  56. if (args == null)
  57. {
  58. return "";
  59. }
  60. string argStr = " [";
  61. for (int arrIndex = 0; arrIndex < args.Length; arrIndex++)
  62. {
  63. argStr += args[arrIndex];
  64. if (arrIndex != args.Length - 1)
  65. {
  66. argStr += ", ";
  67. }
  68. }
  69. argStr += "]";
  70. return argStr;
  71. }
  72. public static string ArrayToString<T>(this T[] args, int index, int count)
  73. {
  74. if (args == null)
  75. {
  76. return "";
  77. }
  78. string argStr = " [";
  79. for (int arrIndex = index; arrIndex < count + index; arrIndex++)
  80. {
  81. argStr += args[arrIndex];
  82. if (arrIndex != args.Length - 1)
  83. {
  84. argStr += ", ";
  85. }
  86. }
  87. argStr += "]";
  88. return argStr;
  89. }
  90. }
  91. }