NameFormat.cs 3.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. namespace Azylee.Core.DataUtils.StringUtils
  6. {
  7. public class NameFormat
  8. {
  9. /// <summary>
  10. /// 转换为驼峰命名
  11. /// </summary>
  12. /// <param name="s"></param>
  13. /// <returns></returns>
  14. public static string ToCamelCase(string s)
  15. {
  16. string result = "";
  17. if (Str.Ok(s))
  18. {
  19. if (s.IndexOf('_') >= 0)
  20. {
  21. bool upFlag = false;
  22. char[] cArray = s.ToArray();
  23. foreach (var c in cArray)
  24. {
  25. if (c == '_')
  26. {
  27. upFlag = true;
  28. continue;
  29. }
  30. if (upFlag)
  31. {
  32. result += c.ToString().ToUpper();
  33. upFlag = false;
  34. }
  35. else
  36. {
  37. result += c.ToString().ToLower();
  38. }
  39. }
  40. }
  41. else
  42. {
  43. result = s;
  44. }
  45. }
  46. return result;
  47. }
  48. /// <summary>
  49. /// 转换为驼峰命名(首字母大写)
  50. /// </summary>
  51. /// <param name="s"></param>
  52. /// <returns></returns>
  53. public static string ToUpCamelCase(string s)
  54. {
  55. string result = "";
  56. if (Str.Ok(s))
  57. {
  58. bool upFlag = false;
  59. char[] cArray = s.ToArray();
  60. for (int i = 0; i < cArray.Length; i++)
  61. {
  62. char c = cArray[i];
  63. if (c == '_')
  64. {
  65. upFlag = true;
  66. continue;
  67. }
  68. if (upFlag || i == 0)
  69. {
  70. result += c.ToString().ToUpper();
  71. upFlag = false;
  72. }
  73. else
  74. {
  75. result += c.ToString().ToLower();
  76. }
  77. }
  78. }
  79. return result;
  80. }
  81. /// <summary>
  82. /// 转换为下划线命名
  83. /// </summary>
  84. /// <param name="s"></param>
  85. /// <returns></returns>
  86. public static string ToUnderline(string s)
  87. {
  88. string result = "";
  89. if (Str.Ok(s))
  90. {
  91. char[] cArray = s.ToArray();
  92. foreach (var c in cArray)
  93. {
  94. char cUpper = char.ToUpper(c);
  95. char cLower = char.ToLower(c);
  96. if (c >= 'A' && c <= 'Z')
  97. {
  98. result += "_";
  99. }
  100. result += char.ToLower(c);
  101. }
  102. }
  103. return result;
  104. }
  105. public static string Format(string s, NameType nameType)
  106. {
  107. switch (nameType)
  108. {
  109. case NameType.CAMEL:
  110. return ToCamelCase(s);
  111. case NameType.UPPER_CAMEL:
  112. return ToUpCamelCase(s);
  113. case NameType.UNDER_LINE:
  114. return ToUnderline(s);
  115. case NameType.NONE:
  116. default:
  117. return s;
  118. }
  119. }
  120. }
  121. }