ExtensionString.cs 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. using UnityEngine;
  2. using System;
  3. using System.Collections;
  4. using System.Text;
  5. public static class ExtensionString
  6. {
  7. public static T ToEnum<T>(this string str)
  8. {
  9. return (T)Enum.Parse(typeof(T), str);
  10. }
  11. public static string Remove(this string str, int startIndex, int endIndex, bool empty)
  12. {
  13. if (startIndex > endIndex)
  14. {
  15. throw new Exception();
  16. }
  17. return str.Remove(startIndex, endIndex - startIndex + 1);
  18. }
  19. public static string ReplaceByLength(this string str, int index, int length, string newStr)
  20. {
  21. str = str.Remove(index, length);
  22. str = str.Insert(index, newStr);
  23. return str;
  24. }
  25. public static string Replace(this string str, int startIndex, int endIndex, string newStr)
  26. {
  27. if (startIndex > endIndex)
  28. {
  29. throw new Exception();
  30. }
  31. str = str.Remove(startIndex, endIndex - startIndex + 1);
  32. str = str.Insert(startIndex, newStr);
  33. return str;
  34. }
  35. public static string Between(this string str, int startIndex, int endIndex)
  36. {
  37. if (startIndex > endIndex)
  38. {
  39. return "";
  40. }
  41. else if (startIndex == endIndex)
  42. {
  43. return str[startIndex].ToString();
  44. }
  45. else
  46. {
  47. return str.Substring(startIndex, endIndex - startIndex + 1);
  48. }
  49. }
  50. public static int GetBytes(this string str)
  51. {
  52. if (str.Equals(string.Empty))
  53. return 0;
  54. int strlen = 0;
  55. ASCIIEncoding strData = new ASCIIEncoding();
  56. //将字符串转换为ASCII编码的字节数字
  57. byte[] strBytes = strData.GetBytes(str);
  58. for (int i = 0; i <= strBytes.Length - 1; i++)
  59. {
  60. if (strBytes[i] == 63) //中文都将编码为ASCII编码63,即"?"号
  61. strlen++;
  62. strlen++;
  63. }
  64. return strlen;
  65. }
  66. }