StringExtensions.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532
  1. using System;
  2. using System.Globalization;
  3. using System.Security.Cryptography;
  4. using System.Text;
  5. using System.Text.RegularExpressions;
  6. using Abp.Collections.Extensions;
  7. namespace Abp.Extensions
  8. {
  9. /// <summary>
  10. /// Extension methods for String class.
  11. /// </summary>
  12. public static class StringExtensions
  13. {
  14. /// <summary>
  15. /// Adds a char to end of given string if it does not ends with the char.
  16. /// </summary>
  17. public static string EnsureEndsWith(this string str, char c)
  18. {
  19. return EnsureEndsWith(str, c, StringComparison.Ordinal);
  20. }
  21. /// <summary>
  22. /// Adds a char to end of given string if it does not ends with the char.
  23. /// </summary>
  24. public static string EnsureEndsWith(this string str, char c, StringComparison comparisonType)
  25. {
  26. if (str == null)
  27. {
  28. throw new ArgumentNullException(nameof(str));
  29. }
  30. if (str.EndsWith(c.ToString(), comparisonType))
  31. {
  32. return str;
  33. }
  34. return str + c;
  35. }
  36. /// <summary>
  37. /// Adds a char to end of given string if it does not ends with the char.
  38. /// </summary>
  39. public static string EnsureEndsWith(this string str, char c, bool ignoreCase, CultureInfo culture)
  40. {
  41. if (str == null)
  42. {
  43. throw new ArgumentNullException(nameof(str));
  44. }
  45. if (str.EndsWith(c.ToString(culture), ignoreCase, culture))
  46. {
  47. return str;
  48. }
  49. return str + c;
  50. }
  51. /// <summary>
  52. /// Adds a char to beginning of given string if it does not starts with the char.
  53. /// </summary>
  54. public static string EnsureStartsWith(this string str, char c)
  55. {
  56. return EnsureStartsWith(str, c, StringComparison.Ordinal);
  57. }
  58. /// <summary>
  59. /// Adds a char to beginning of given string if it does not starts with the char.
  60. /// </summary>
  61. public static string EnsureStartsWith(this string str, char c, StringComparison comparisonType)
  62. {
  63. if (str == null)
  64. {
  65. throw new ArgumentNullException(nameof(str));
  66. }
  67. if (str.StartsWith(c.ToString(), comparisonType))
  68. {
  69. return str;
  70. }
  71. return c + str;
  72. }
  73. /// <summary>
  74. /// Adds a char to beginning of given string if it does not starts with the char.
  75. /// </summary>
  76. public static string EnsureStartsWith(this string str, char c, bool ignoreCase, CultureInfo culture)
  77. {
  78. if (str == null)
  79. {
  80. throw new ArgumentNullException("str");
  81. }
  82. if (str.StartsWith(c.ToString(culture), ignoreCase, culture))
  83. {
  84. return str;
  85. }
  86. return c + str;
  87. }
  88. /// <summary>
  89. /// Indicates whether this string is null or an System.String.Empty string.
  90. /// </summary>
  91. public static bool IsNullOrEmpty(this string str)
  92. {
  93. return string.IsNullOrEmpty(str);
  94. }
  95. /// <summary>
  96. /// indicates whether this string is null, empty, or consists only of white-space characters.
  97. /// </summary>
  98. public static bool IsNullOrWhiteSpace(this string str)
  99. {
  100. return string.IsNullOrWhiteSpace(str);
  101. }
  102. /// <summary>
  103. /// Gets a substring of a string from beginning of the string.
  104. /// </summary>
  105. /// <exception cref="ArgumentNullException">Thrown if <paramref name="str"/> is null</exception>
  106. /// <exception cref="ArgumentException">Thrown if <paramref name="len"/> is bigger that string's length</exception>
  107. public static string Left(this string str, int len)
  108. {
  109. if (str == null)
  110. {
  111. throw new ArgumentNullException("str");
  112. }
  113. if (str.Length < len)
  114. {
  115. throw new ArgumentException("len argument can not be bigger than given string's length!");
  116. }
  117. return str.Substring(0, len);
  118. }
  119. /// <summary>
  120. /// Converts line endings in the string to <see cref="Environment.NewLine"/>.
  121. /// </summary>
  122. public static string NormalizeLineEndings(this string str)
  123. {
  124. return str.Replace("\r\n", "\n").Replace("\r", "\n").Replace("\n", Environment.NewLine);
  125. }
  126. /// <summary>
  127. /// Gets index of nth occurence of a char in a string.
  128. /// </summary>
  129. /// <param name="str">source string to be searched</param>
  130. /// <param name="c">Char to search in <see cref="str"/></param>
  131. /// <param name="n">Count of the occurence</param>
  132. public static int NthIndexOf(this string str, char c, int n)
  133. {
  134. if (str == null)
  135. {
  136. throw new ArgumentNullException(nameof(str));
  137. }
  138. var count = 0;
  139. for (var i = 0; i < str.Length; i++)
  140. {
  141. if (str[i] != c)
  142. {
  143. continue;
  144. }
  145. if ((++count) == n)
  146. {
  147. return i;
  148. }
  149. }
  150. return -1;
  151. }
  152. /// <summary>
  153. /// Removes first occurrence of the given postfixes from end of the given string.
  154. /// Ordering is important. If one of the postFixes is matched, others will not be tested.
  155. /// </summary>
  156. /// <param name="str">The string.</param>
  157. /// <param name="postFixes">one or more postfix.</param>
  158. /// <returns>Modified string or the same string if it has not any of given postfixes</returns>
  159. public static string RemovePostFix(this string str, params string[] postFixes)
  160. {
  161. if (str == null)
  162. {
  163. return null;
  164. }
  165. if (str == string.Empty)
  166. {
  167. return string.Empty;
  168. }
  169. if (postFixes.IsNullOrEmpty())
  170. {
  171. return str;
  172. }
  173. foreach (var postFix in postFixes)
  174. {
  175. if (str.EndsWith(postFix))
  176. {
  177. return str.Left(str.Length - postFix.Length);
  178. }
  179. }
  180. return str;
  181. }
  182. /// <summary>
  183. /// Removes first occurrence of the given prefixes from beginning of the given string.
  184. /// Ordering is important. If one of the preFixes is matched, others will not be tested.
  185. /// </summary>
  186. /// <param name="str">The string.</param>
  187. /// <param name="preFixes">one or more prefix.</param>
  188. /// <returns>Modified string or the same string if it has not any of given prefixes</returns>
  189. public static string RemovePreFix(this string str, params string[] preFixes)
  190. {
  191. if (str == null)
  192. {
  193. return null;
  194. }
  195. if (str == string.Empty)
  196. {
  197. return string.Empty;
  198. }
  199. if (preFixes.IsNullOrEmpty())
  200. {
  201. return str;
  202. }
  203. foreach (var preFix in preFixes)
  204. {
  205. if (str.StartsWith(preFix))
  206. {
  207. return str.Right(str.Length - preFix.Length);
  208. }
  209. }
  210. return str;
  211. }
  212. /// <summary>
  213. /// Gets a substring of a string from end of the string.
  214. /// </summary>
  215. /// <exception cref="ArgumentNullException">Thrown if <paramref name="str"/> is null</exception>
  216. /// <exception cref="ArgumentException">Thrown if <paramref name="len"/> is bigger that string's length</exception>
  217. public static string Right(this string str, int len)
  218. {
  219. if (str == null)
  220. {
  221. throw new ArgumentNullException("str");
  222. }
  223. if (str.Length < len)
  224. {
  225. throw new ArgumentException("len argument can not be bigger than given string's length!");
  226. }
  227. return str.Substring(str.Length - len, len);
  228. }
  229. /// <summary>
  230. /// Uses string.Split method to split given string by given separator.
  231. /// </summary>
  232. public static string[] Split(this string str, string separator)
  233. {
  234. return str.Split(new[] { separator }, StringSplitOptions.None);
  235. }
  236. /// <summary>
  237. /// Uses string.Split method to split given string by given separator.
  238. /// </summary>
  239. public static string[] Split(this string str, string separator, StringSplitOptions options)
  240. {
  241. return str.Split(new[] { separator }, options);
  242. }
  243. /// <summary>
  244. /// Uses string.Split method to split given string by <see cref="Environment.NewLine"/>.
  245. /// </summary>
  246. public static string[] SplitToLines(this string str)
  247. {
  248. return str.Split(Environment.NewLine);
  249. }
  250. /// <summary>
  251. /// Uses string.Split method to split given string by <see cref="Environment.NewLine"/>.
  252. /// </summary>
  253. public static string[] SplitToLines(this string str, StringSplitOptions options)
  254. {
  255. return str.Split(Environment.NewLine, options);
  256. }
  257. /// <summary>
  258. /// Converts PascalCase string to camelCase string.
  259. /// </summary>
  260. /// <param name="str">String to convert</param>
  261. /// <param name="invariantCulture">Invariant culture</param>
  262. /// <returns>camelCase of the string</returns>
  263. public static string ToCamelCase(this string str, bool invariantCulture = true)
  264. {
  265. if (string.IsNullOrWhiteSpace(str))
  266. {
  267. return str;
  268. }
  269. if (str.Length == 1)
  270. {
  271. return invariantCulture ? str.ToLowerInvariant() : str.ToLower();
  272. }
  273. return (invariantCulture ? char.ToLowerInvariant(str[0]) : char.ToLower(str[0])) + str.Substring(1);
  274. }
  275. /// <summary>
  276. /// Converts PascalCase string to camelCase string in specified culture.
  277. /// </summary>
  278. /// <param name="str">String to convert</param>
  279. /// <param name="culture">An object that supplies culture-specific casing rules</param>
  280. /// <returns>camelCase of the string</returns>
  281. public static string ToCamelCase(this string str, CultureInfo culture)
  282. {
  283. if (string.IsNullOrWhiteSpace(str))
  284. {
  285. return str;
  286. }
  287. if (str.Length == 1)
  288. {
  289. return str.ToLower(culture);
  290. }
  291. return char.ToLower(str[0], culture) + str.Substring(1);
  292. }
  293. /// <summary>
  294. /// Converts given PascalCase/camelCase string to sentence (by splitting words by space).
  295. /// Example: "ThisIsSampleSentence" is converted to "This is a sample sentence".
  296. /// </summary>
  297. /// <param name="str">String to convert.</param>
  298. /// <param name="invariantCulture">Invariant culture</param>
  299. public static string ToSentenceCase(this string str, bool invariantCulture = false)
  300. {
  301. if (string.IsNullOrWhiteSpace(str))
  302. {
  303. return str;
  304. }
  305. return Regex.Replace(
  306. str,
  307. "[a-z][A-Z]",
  308. m => m.Value[0] + " " + (invariantCulture ? char.ToLowerInvariant(m.Value[1]) : char.ToLower(m.Value[1]))
  309. );
  310. }
  311. /// <summary>
  312. /// Converts given PascalCase/camelCase string to sentence (by splitting words by space).
  313. /// Example: "ThisIsSampleSentence" is converted to "This is a sample sentence".
  314. /// </summary>
  315. /// <param name="str">String to convert.</param>
  316. /// <param name="culture">An object that supplies culture-specific casing rules.</param>
  317. public static string ToSentenceCase(this string str, CultureInfo culture)
  318. {
  319. if (string.IsNullOrWhiteSpace(str))
  320. {
  321. return str;
  322. }
  323. return Regex.Replace(str, "[a-z][A-Z]", m => m.Value[0] + " " + char.ToLower(m.Value[1], culture));
  324. }
  325. /// <summary>
  326. /// Converts string to enum value.
  327. /// </summary>
  328. /// <typeparam name="T">Type of enum</typeparam>
  329. /// <param name="value">String value to convert</param>
  330. /// <returns>Returns enum object</returns>
  331. public static T ToEnum<T>(this string value)
  332. where T : struct
  333. {
  334. if (value == null)
  335. {
  336. throw new ArgumentNullException(nameof(value));
  337. }
  338. return (T)Enum.Parse(typeof(T), value);
  339. }
  340. /// <summary>
  341. /// Converts string to enum value.
  342. /// </summary>
  343. /// <typeparam name="T">Type of enum</typeparam>
  344. /// <param name="value">String value to convert</param>
  345. /// <param name="ignoreCase">Ignore case</param>
  346. /// <returns>Returns enum object</returns>
  347. public static T ToEnum<T>(this string value, bool ignoreCase)
  348. where T : struct
  349. {
  350. if (value == null)
  351. {
  352. throw new ArgumentNullException(nameof(value));
  353. }
  354. return (T)Enum.Parse(typeof(T), value, ignoreCase);
  355. }
  356. public static string ToMd5(this string str)
  357. {
  358. using (var md5 = MD5.Create())
  359. {
  360. var inputBytes = Encoding.UTF8.GetBytes(str);
  361. var hashBytes = md5.ComputeHash(inputBytes);
  362. var sb = new StringBuilder();
  363. foreach (var hashByte in hashBytes)
  364. {
  365. sb.Append(hashByte.ToString("X2"));
  366. }
  367. return sb.ToString();
  368. }
  369. }
  370. /// <summary>
  371. /// Converts camelCase string to PascalCase string.
  372. /// </summary>
  373. /// <param name="str">String to convert</param>
  374. /// <param name="invariantCulture">Invariant culture</param>
  375. /// <returns>PascalCase of the string</returns>
  376. public static string ToPascalCase(this string str, bool invariantCulture = true)
  377. {
  378. if (string.IsNullOrWhiteSpace(str))
  379. {
  380. return str;
  381. }
  382. if (str.Length == 1)
  383. {
  384. return invariantCulture ? str.ToUpperInvariant(): str.ToUpper();
  385. }
  386. return (invariantCulture ? char.ToUpperInvariant(str[0]) : char.ToUpper(str[0])) + str.Substring(1);
  387. }
  388. /// <summary>
  389. /// Converts camelCase string to PascalCase string in specified culture.
  390. /// </summary>
  391. /// <param name="str">String to convert</param>
  392. /// <param name="culture">An object that supplies culture-specific casing rules</param>
  393. /// <returns>PascalCase of the string</returns>
  394. public static string ToPascalCase(this string str, CultureInfo culture)
  395. {
  396. if (string.IsNullOrWhiteSpace(str))
  397. {
  398. return str;
  399. }
  400. if (str.Length == 1)
  401. {
  402. return str.ToUpper(culture);
  403. }
  404. return char.ToUpper(str[0], culture) + str.Substring(1);
  405. }
  406. /// <summary>
  407. /// Gets a substring of a string from beginning of the string if it exceeds maximum length.
  408. /// </summary>
  409. /// <exception cref="ArgumentNullException">Thrown if <paramref name="str"/> is null</exception>
  410. public static string Truncate(this string str, int maxLength)
  411. {
  412. if (str == null)
  413. {
  414. return null;
  415. }
  416. if (str.Length <= maxLength)
  417. {
  418. return str;
  419. }
  420. return str.Left(maxLength);
  421. }
  422. /// <summary>
  423. /// Gets a substring of a string from beginning of the string if it exceeds maximum length.
  424. /// It adds a "..." postfix to end of the string if it's truncated.
  425. /// Returning string can not be longer than maxLength.
  426. /// </summary>
  427. /// <exception cref="ArgumentNullException">Thrown if <paramref name="str"/> is null</exception>
  428. public static string TruncateWithPostfix(this string str, int maxLength)
  429. {
  430. return TruncateWithPostfix(str, maxLength, "...");
  431. }
  432. /// <summary>
  433. /// Gets a substring of a string from beginning of the string if it exceeds maximum length.
  434. /// It adds given <paramref name="postfix"/> to end of the string if it's truncated.
  435. /// Returning string can not be longer than maxLength.
  436. /// </summary>
  437. /// <exception cref="ArgumentNullException">Thrown if <paramref name="str"/> is null</exception>
  438. public static string TruncateWithPostfix(this string str, int maxLength, string postfix)
  439. {
  440. if (str == null)
  441. {
  442. return null;
  443. }
  444. if (str == string.Empty || maxLength == 0)
  445. {
  446. return string.Empty;
  447. }
  448. if (str.Length <= maxLength)
  449. {
  450. return str;
  451. }
  452. if (maxLength <= postfix.Length)
  453. {
  454. return postfix.Left(maxLength);
  455. }
  456. return str.Left(maxLength - postfix.Length) + postfix;
  457. }
  458. }
  459. }