ExtensionString.cs 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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 Replace(this string str, int startIndex, int endIndex, string newStr)
  20. {
  21. if (startIndex > endIndex)
  22. {
  23. throw new Exception();
  24. }
  25. str = str.Remove(startIndex, endIndex - startIndex + 1);
  26. str = str.Insert(startIndex, newStr);
  27. return str;
  28. }
  29. public static string Between(this string str, int startIndex, int endIndex)
  30. {
  31. if (startIndex > endIndex)
  32. {
  33. return "";
  34. }
  35. else if (startIndex == endIndex)
  36. {
  37. return str[startIndex].ToString();
  38. }
  39. else
  40. {
  41. return str.Substring(startIndex, endIndex - startIndex + 1);
  42. }
  43. }
  44. public static int GetBytes(this string str)
  45. {
  46. if (str.Equals(string.Empty))
  47. return 0;
  48. int strlen = 0;
  49. ASCIIEncoding strData = new ASCIIEncoding();
  50. //将字符串转换为ASCII编码的字节数字
  51. byte[] strBytes = strData.GetBytes(str);
  52. for (int i = 0; i <= strBytes.Length - 1; i++)
  53. {
  54. if (strBytes[i] == 63) //中文都将编码为ASCII编码63,即"?"号
  55. strlen++;
  56. strlen++;
  57. }
  58. return strlen;
  59. }
  60. }