StringExt.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Text;
  6. namespace Quadarax.Foundation.Core.Value.Extensions
  7. {
  8. public static class StringExt
  9. {
  10. /// <summary>
  11. /// Default string comparer for like operator.
  12. /// </summary>
  13. public static IEqualityComparer<string> DefaultLikeComparer { get; set; } = new StringPatternComparer();
  14. public static string Align(this string value, int size)
  15. {
  16. if (string.IsNullOrEmpty(value)) return new string(' ', size);
  17. if (value.Length < size)
  18. return value + new string(' ', size - value.Length);
  19. return Truncate(value, size);
  20. }
  21. public static string Truncate(this string value, int maxLength)
  22. {
  23. if (string.IsNullOrEmpty(value)) return value;
  24. return value.Length <= maxLength ? value : value.Substring(0, maxLength);
  25. }
  26. public static int SeparateValueCount(this string value, string separator)
  27. {
  28. var nSepLen = separator.Length;
  29. var nStrLen = value.Length;
  30. if (nStrLen == 0 || nSepLen == 0)
  31. return nSepLen == 0 && nStrLen > 0 ? 1 : 0;
  32. var nCnt = 0;
  33. var nPos = value.IndexOf(separator, StringComparison.Ordinal);
  34. while (nPos >= 0)
  35. {
  36. nCnt++;
  37. nPos = value.IndexOf(separator, nPos + nSepLen, StringComparison.Ordinal);
  38. }
  39. return nCnt + 1;
  40. }
  41. public static string SeparateValue(this string value, string separator, int zeroBasedIndex)
  42. {
  43. var nSepLen = separator.Length;
  44. var nStrLen = value.Length;
  45. if (nStrLen == 0 || nSepLen == 0 || nSepLen > nStrLen)
  46. throw new IndexOutOfRangeException("SeparateValue method has index out of range.");
  47. var nLastPos = 0;
  48. var nPos = value.IndexOf(separator, StringComparison.Ordinal);
  49. while (nPos >= 0)
  50. {
  51. if (zeroBasedIndex == 0)
  52. break;
  53. nLastPos = nPos + nSepLen;
  54. nPos = value.IndexOf(separator, nPos + nSepLen, StringComparison.Ordinal);
  55. zeroBasedIndex--;
  56. }
  57. if (zeroBasedIndex > 0)
  58. throw new IndexOutOfRangeException("SeparateValue method has index out of range.");
  59. return value.Substring(nLastPos, nPos == -1 ? nStrLen - nLastPos : nPos - nLastPos);
  60. }
  61. public static string SeparateValueLast(this string value, string separator)
  62. {
  63. var nSepLen = separator.Length;
  64. var nStrLen = value.Length;
  65. if (nStrLen == 0 || nSepLen == 0 || nSepLen > nStrLen)
  66. throw new IndexOutOfRangeException("SeparateValue method has index out of range.");
  67. return value.SeparateValue(separator, value.SeparateValueCount(separator) - 1);
  68. }
  69. public static string RemoveLast(this string value)
  70. {
  71. return value.Length == 0 ? string.Empty : value.Substring(0, value.Length - 1);
  72. }
  73. public static string RemoveFirst(this string value)
  74. {
  75. return value.Length == 0 ? string.Empty : value.Substring(1, value.Length - 1);
  76. }
  77. public static int MaxLineChars(this string value)
  78. {
  79. var aParts = value.Split("/n");
  80. return aParts.Length > 0 ? aParts.Max(x => x.Length) : value.Length;
  81. }
  82. public static string[] Split(this string value, string separator)
  83. {
  84. return value.Split(new[] { separator }, StringSplitOptions.RemoveEmptyEntries);
  85. }
  86. public static Tuple<string, string>[] Extract(this string value, params string[] hashes) //hashtype, tashname
  87. {
  88. var oResult = new List<Tuple<string, string>>();
  89. if (hashes.Length == 0)
  90. return new Tuple<string, string>[0];
  91. var nLenIndex = value.Length + 1;
  92. foreach (var sHash in hashes)
  93. {
  94. var bBeginBlock = true;
  95. var nPos = value.IndexOf(sHash, StringComparison.InvariantCulture);
  96. var nLenHash = sHash.Length;
  97. if (nPos < 0)
  98. continue;
  99. while (nPos >= 0)
  100. {
  101. if (nPos + nLenHash > nLenIndex)
  102. break;
  103. var nEndPos = value.IndexOf(sHash, nPos + nLenHash, StringComparison.InvariantCulture);
  104. if (nEndPos < 0)
  105. break;
  106. if (bBeginBlock)
  107. {
  108. var oEntry = new Tuple<string, string>(sHash, value.Substring(nPos + nLenHash, nEndPos - nPos - nLenHash));
  109. if (!oResult.Contains(oEntry))
  110. oResult.Add(oEntry);
  111. }
  112. nPos = nEndPos;
  113. bBeginBlock = !bBeginBlock;
  114. }
  115. }
  116. return oResult.ToArray();
  117. }
  118. public static string EnsurePathBackslash(this string value)
  119. {
  120. if (string.IsNullOrEmpty(value))
  121. return value;
  122. value = value.Trim();
  123. if (value.EndsWith(Path.DirectorySeparatorChar))
  124. return value;
  125. return value + Path.DirectorySeparatorChar;
  126. }
  127. public static string EnsurePathNonBackslash(this string value)
  128. {
  129. if (string.IsNullOrEmpty(value))
  130. return value;
  131. value = value.Trim();
  132. if (!value.EndsWith(Path.DirectorySeparatorChar))
  133. return value;
  134. return value.RemoveLast();
  135. }
  136. public static string RemoveWhitespace(this string input)
  137. {
  138. return new string(input.ToCharArray()
  139. .Where(c => !Char.IsWhiteSpace(c))
  140. .ToArray());
  141. }
  142. /// <summary>
  143. /// Performs like operator on input string. customComparer can be provides to override default comparer.
  144. /// </summary>
  145. /// <param name="input">Input string to compare</param>
  146. /// <param name="searchPattern">Search pattern corresponds with comparer implementation.</param>
  147. /// <param name="customComparer">Custom comparer. If not set, use default comparer (defined in <see cref="DefaultLikeComparer"/>)</param>
  148. /// <returns></returns>
  149. public static bool Like(this string input, string searchPattern, IEqualityComparer<string>? customComparer = null)
  150. {
  151. customComparer ??= DefaultLikeComparer;
  152. return customComparer.Equals(input, searchPattern);
  153. }
  154. /// <summary>
  155. /// Splits a string by the specified separator, but ignores separators that are within brackets/quotes.
  156. /// </summary>
  157. /// <param name="value">The string to split</param>
  158. /// <param name="separator">The separator string to split on</param>
  159. /// <param name="beginBracket">The opening bracket/quote character(s)</param>
  160. /// <param name="endBracket">The closing bracket/quote character(s). If null, uses the same as beginBracket</param>
  161. /// <param name="removeEmptyItems">If true, removes empty entries from the result</param>
  162. /// <param name="trimValues">If true, trims whitespace from each result value</param>
  163. /// <param name="keepBracket">If true, keeps the begin and end brackets in the result</param>
  164. /// <returns>Array of split string parts</returns>
  165. public static string[] SplitQuoted(this string value, string separator, string beginBracket, string? endBracket = null, bool removeEmptyItems = true, bool trimValues = true, bool keepBracket = false)
  166. {
  167. if (string.IsNullOrEmpty(value))
  168. return new string[] { value ?? string.Empty };
  169. if (string.IsNullOrEmpty(separator))
  170. throw new ArgumentException("Separator cannot be null or empty", nameof(separator));
  171. if (string.IsNullOrEmpty(beginBracket))
  172. throw new ArgumentException("Begin bracket cannot be null or empty", nameof(beginBracket));
  173. // If endBracket is not specified, use the same as beginBracket
  174. endBracket ??= beginBracket;
  175. var result = new List<string>();
  176. var currentPart = new StringBuilder();
  177. var i = 0;
  178. while (i < value.Length)
  179. {
  180. // Check if we're at the start of a separator
  181. if (i <= value.Length - separator.Length &&
  182. value.Substring(i, separator.Length) == separator)
  183. {
  184. // Found separator outside brackets, so add current part to result
  185. result.Add(currentPart.ToString());
  186. currentPart.Clear();
  187. i += separator.Length;
  188. continue;
  189. }
  190. // Check if we're at the start of a begin bracket
  191. if (i <= value.Length - beginBracket.Length &&
  192. value.Substring(i, beginBracket.Length) == beginBracket)
  193. {
  194. // Found begin bracket, add it to current part if keepBracket is true
  195. if (keepBracket)
  196. {
  197. currentPart.Append(beginBracket);
  198. }
  199. i += beginBracket.Length;
  200. // Now find the matching end bracket
  201. var bracketDepth = 1;
  202. while (i < value.Length && bracketDepth > 0)
  203. {
  204. // Check for end brackets first (important for single-character brackets like quotes)
  205. if (i <= value.Length - endBracket.Length &&
  206. value.Substring(i, endBracket.Length) == endBracket)
  207. {
  208. i += endBracket.Length;
  209. bracketDepth--;
  210. // Add the end bracket if we're still nested or if keepBracket is true for outermost
  211. if (bracketDepth > 0 || keepBracket)
  212. {
  213. currentPart.Append(endBracket);
  214. }
  215. }
  216. // Check for nested begin brackets (only if different from end bracket or if we haven't found end bracket)
  217. else if (beginBracket != endBracket &&
  218. i <= value.Length - beginBracket.Length &&
  219. value.Substring(i, beginBracket.Length) == beginBracket)
  220. {
  221. currentPart.Append(beginBracket);
  222. i += beginBracket.Length;
  223. bracketDepth++;
  224. }
  225. else
  226. {
  227. // Regular character inside brackets
  228. currentPart.Append(value[i]);
  229. i++;
  230. }
  231. }
  232. continue;
  233. }
  234. // Regular character outside brackets
  235. currentPart.Append(value[i]);
  236. i++;
  237. }
  238. // Add the last part
  239. result.Add(currentPart.ToString());
  240. // Process the result based on options
  241. var finalResult = new List<string>();
  242. foreach (var part in result)
  243. {
  244. var processedPart = trimValues ? part.Trim() : part;
  245. if (!removeEmptyItems || !string.IsNullOrEmpty(processedPart))
  246. {
  247. finalResult.Add(processedPart);
  248. }
  249. }
  250. return finalResult.ToArray();
  251. }
  252. }
  253. }