StringExtensions.cs 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Globalization;
  4. using System.Runtime.CompilerServices;
  5. using System.Security;
  6. using System.Text;
  7. using System.Text.RegularExpressions;
  8. namespace Godot
  9. {
  10. public static class StringExtensions
  11. {
  12. private static int GetSliceCount(this string instance, string splitter)
  13. {
  14. if (string.IsNullOrEmpty(instance) || string.IsNullOrEmpty(splitter))
  15. return 0;
  16. int pos = 0;
  17. int slices = 1;
  18. while ((pos = instance.Find(splitter, pos, caseSensitive: true)) >= 0)
  19. {
  20. slices++;
  21. pos += splitter.Length;
  22. }
  23. return slices;
  24. }
  25. private static string GetSliceCharacter(this string instance, char splitter, int slice)
  26. {
  27. if (!string.IsNullOrEmpty(instance) && slice >= 0)
  28. {
  29. int i = 0;
  30. int prev = 0;
  31. int count = 0;
  32. while (true)
  33. {
  34. bool end = instance.Length <= i;
  35. if (end || instance[i] == splitter)
  36. {
  37. if (slice == count)
  38. {
  39. return instance.Substring(prev, i - prev);
  40. }
  41. else if (end)
  42. {
  43. return string.Empty;
  44. }
  45. count++;
  46. prev = i + 1;
  47. }
  48. i++;
  49. }
  50. }
  51. return string.Empty;
  52. }
  53. /// <summary>
  54. /// If the string is a path to a file, return the path to the file without the extension.
  55. /// </summary>
  56. public static string GetBaseName(this string instance)
  57. {
  58. int index = instance.LastIndexOf('.');
  59. if (index > 0)
  60. return instance.Substring(0, index);
  61. return instance;
  62. }
  63. /// <summary>
  64. /// Return <see langword="true"/> if the strings begins with the given string.
  65. /// </summary>
  66. public static bool BeginsWith(this string instance, string text)
  67. {
  68. return instance.StartsWith(text);
  69. }
  70. /// <summary>
  71. /// Return the bigrams (pairs of consecutive letters) of this string.
  72. /// </summary>
  73. public static string[] Bigrams(this string instance)
  74. {
  75. var b = new string[instance.Length - 1];
  76. for (int i = 0; i < b.Length; i++)
  77. {
  78. b[i] = instance.Substring(i, 2);
  79. }
  80. return b;
  81. }
  82. /// <summary>
  83. /// Converts a string containing a binary number into an integer.
  84. /// Binary strings can either be prefixed with `0b` or not,
  85. /// and they can also start with a `-` before the optional prefix.
  86. /// </summary>
  87. /// <param name="instance">The string to convert.</param>
  88. /// <returns>The converted string.</returns>
  89. public static int BinToInt(this string instance)
  90. {
  91. if (instance.Length == 0)
  92. {
  93. return 0;
  94. }
  95. int sign = 1;
  96. if (instance[0] == '-')
  97. {
  98. sign = -1;
  99. instance = instance.Substring(1);
  100. }
  101. if (instance.StartsWith("0b"))
  102. {
  103. instance = instance.Substring(2);
  104. }
  105. return sign * Convert.ToInt32(instance, 2);
  106. }
  107. /// <summary>
  108. /// Return the amount of substrings in string.
  109. /// </summary>
  110. public static int Count(this string instance, string what, bool caseSensitive = true, int from = 0, int to = 0)
  111. {
  112. if (what.Length == 0)
  113. {
  114. return 0;
  115. }
  116. int len = instance.Length;
  117. int slen = what.Length;
  118. if (len < slen)
  119. {
  120. return 0;
  121. }
  122. string str;
  123. if (from >= 0 && to >= 0)
  124. {
  125. if (to == 0)
  126. {
  127. to = len;
  128. }
  129. else if (from >= to)
  130. {
  131. return 0;
  132. }
  133. if (from == 0 && to == len)
  134. {
  135. str = instance;
  136. }
  137. else
  138. {
  139. str = instance.Substring(from, to - from);
  140. }
  141. }
  142. else
  143. {
  144. return 0;
  145. }
  146. int c = 0;
  147. int idx;
  148. do
  149. {
  150. idx = str.IndexOf(what, caseSensitive ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase);
  151. if (idx != -1)
  152. {
  153. str = str.Substring(idx + slen);
  154. ++c;
  155. }
  156. } while (idx != -1);
  157. return c;
  158. }
  159. /// <summary>
  160. /// Return a copy of the string with special characters escaped using the C language standard.
  161. /// </summary>
  162. public static string CEscape(this string instance)
  163. {
  164. var sb = new StringBuilder(string.Copy(instance));
  165. sb.Replace("\\", "\\\\");
  166. sb.Replace("\a", "\\a");
  167. sb.Replace("\b", "\\b");
  168. sb.Replace("\f", "\\f");
  169. sb.Replace("\n", "\\n");
  170. sb.Replace("\r", "\\r");
  171. sb.Replace("\t", "\\t");
  172. sb.Replace("\v", "\\v");
  173. sb.Replace("\'", "\\'");
  174. sb.Replace("\"", "\\\"");
  175. sb.Replace("?", "\\?");
  176. return sb.ToString();
  177. }
  178. /// <summary>
  179. /// Return a copy of the string with escaped characters replaced by their meanings
  180. /// according to the C language standard.
  181. /// </summary>
  182. public static string CUnescape(this string instance)
  183. {
  184. var sb = new StringBuilder(string.Copy(instance));
  185. sb.Replace("\\a", "\a");
  186. sb.Replace("\\b", "\b");
  187. sb.Replace("\\f", "\f");
  188. sb.Replace("\\n", "\n");
  189. sb.Replace("\\r", "\r");
  190. sb.Replace("\\t", "\t");
  191. sb.Replace("\\v", "\v");
  192. sb.Replace("\\'", "\'");
  193. sb.Replace("\\\"", "\"");
  194. sb.Replace("\\?", "?");
  195. sb.Replace("\\\\", "\\");
  196. return sb.ToString();
  197. }
  198. /// <summary>
  199. /// Change the case of some letters. Replace underscores with spaces, convert all letters
  200. /// to lowercase then capitalize first and every letter following the space character.
  201. /// For <c>capitalize camelCase mixed_with_underscores</c> it will return
  202. /// <c>Capitalize Camelcase Mixed With Underscores</c>.
  203. /// </summary>
  204. public static string Capitalize(this string instance)
  205. {
  206. string aux = instance.Replace("_", " ").ToLower();
  207. var cap = string.Empty;
  208. for (int i = 0; i < aux.GetSliceCount(" "); i++)
  209. {
  210. string slice = aux.GetSliceCharacter(' ', i);
  211. if (slice.Length > 0)
  212. {
  213. slice = char.ToUpper(slice[0]) + slice.Substring(1);
  214. if (i > 0)
  215. cap += " ";
  216. cap += slice;
  217. }
  218. }
  219. return cap;
  220. }
  221. /// <summary>
  222. /// Perform a case-sensitive comparison to another string, return -1 if less, 0 if equal and +1 if greater.
  223. /// </summary>
  224. public static int CasecmpTo(this string instance, string to)
  225. {
  226. return instance.CompareTo(to, caseSensitive: true);
  227. }
  228. /// <summary>
  229. /// Perform a comparison to another string, return -1 if less, 0 if equal and +1 if greater.
  230. /// </summary>
  231. public static int CompareTo(this string instance, string to, bool caseSensitive = true)
  232. {
  233. if (string.IsNullOrEmpty(instance))
  234. return string.IsNullOrEmpty(to) ? 0 : -1;
  235. if (string.IsNullOrEmpty(to))
  236. return 1;
  237. int instanceIndex = 0;
  238. int toIndex = 0;
  239. if (caseSensitive) // Outside while loop to avoid checking multiple times, despite some code duplication.
  240. {
  241. while (true)
  242. {
  243. if (to[toIndex] == 0 && instance[instanceIndex] == 0)
  244. return 0; // We're equal
  245. if (instance[instanceIndex] == 0)
  246. return -1; // If this is empty, and the other one is not, then we're less... I think?
  247. if (to[toIndex] == 0)
  248. return 1; // Otherwise the other one is smaller...
  249. if (instance[instanceIndex] < to[toIndex]) // More than
  250. return -1;
  251. if (instance[instanceIndex] > to[toIndex]) // Less than
  252. return 1;
  253. instanceIndex++;
  254. toIndex++;
  255. }
  256. }
  257. else
  258. {
  259. while (true)
  260. {
  261. if (to[toIndex] == 0 && instance[instanceIndex] == 0)
  262. return 0; // We're equal
  263. if (instance[instanceIndex] == 0)
  264. return -1; // If this is empty, and the other one is not, then we're less... I think?
  265. if (to[toIndex] == 0)
  266. return 1; // Otherwise the other one is smaller..
  267. if (char.ToUpper(instance[instanceIndex]) < char.ToUpper(to[toIndex])) // More than
  268. return -1;
  269. if (char.ToUpper(instance[instanceIndex]) > char.ToUpper(to[toIndex])) // Less than
  270. return 1;
  271. instanceIndex++;
  272. toIndex++;
  273. }
  274. }
  275. }
  276. /// <summary>
  277. /// Return <see langword="true"/> if the strings ends with the given string.
  278. /// </summary>
  279. public static bool EndsWith(this string instance, string text)
  280. {
  281. return instance.EndsWith(text);
  282. }
  283. /// <summary>
  284. /// Erase <paramref name="chars"/> characters from the string starting from <paramref name="pos"/>.
  285. /// </summary>
  286. public static void Erase(this StringBuilder instance, int pos, int chars)
  287. {
  288. instance.Remove(pos, chars);
  289. }
  290. /// <summary>
  291. /// If the string is a path to a file, return the extension.
  292. /// </summary>
  293. public static string GetExtension(this string instance)
  294. {
  295. int pos = instance.FindLast(".");
  296. if (pos < 0)
  297. return instance;
  298. return instance.Substring(pos + 1);
  299. }
  300. /// <summary>
  301. /// Find the first occurrence of a substring. Optionally, the search starting position can be passed.
  302. /// </summary>
  303. /// <returns>The starting position of the substring, or -1 if not found.</returns>
  304. public static int Find(this string instance, string what, int from = 0, bool caseSensitive = true)
  305. {
  306. return instance.IndexOf(what, from, caseSensitive ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase);
  307. }
  308. /// <summary>
  309. /// Find the first occurrence of a char. Optionally, the search starting position can be passed.
  310. /// </summary>
  311. /// <returns>The first instance of the char, or -1 if not found.</returns>
  312. public static int Find(this string instance, char what, int from = 0, bool caseSensitive = true)
  313. {
  314. // TODO: Could be more efficient if we get a char version of `IndexOf`.
  315. // See https://github.com/dotnet/runtime/issues/44116
  316. return instance.IndexOf(what.ToString(), from, caseSensitive ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase);
  317. }
  318. /// <summary>Find the last occurrence of a substring.</summary>
  319. /// <returns>The starting position of the substring, or -1 if not found.</returns>
  320. public static int FindLast(this string instance, string what, bool caseSensitive = true)
  321. {
  322. return instance.FindLast(what, instance.Length - 1, caseSensitive);
  323. }
  324. /// <summary>Find the last occurrence of a substring specifying the search starting position.</summary>
  325. /// <returns>The starting position of the substring, or -1 if not found.</returns>
  326. public static int FindLast(this string instance, string what, int from, bool caseSensitive = true)
  327. {
  328. return instance.LastIndexOf(what, from, caseSensitive ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase);
  329. }
  330. /// <summary>
  331. /// Find the first occurrence of a substring but search as case-insensitive.
  332. /// Optionally, the search starting position can be passed.
  333. /// </summary>
  334. /// <returns>The starting position of the substring, or -1 if not found.</returns>
  335. public static int FindN(this string instance, string what, int from = 0)
  336. {
  337. return instance.IndexOf(what, from, StringComparison.OrdinalIgnoreCase);
  338. }
  339. /// <summary>
  340. /// If the string is a path to a file, return the base directory.
  341. /// </summary>
  342. public static string GetBaseDir(this string instance)
  343. {
  344. int basepos = instance.Find("://");
  345. string rs;
  346. var @base = string.Empty;
  347. if (basepos != -1)
  348. {
  349. var end = basepos + 3;
  350. rs = instance.Substring(end);
  351. @base = instance.Substring(0, end);
  352. }
  353. else
  354. {
  355. if (instance.BeginsWith("/"))
  356. {
  357. rs = instance.Substring(1);
  358. @base = "/";
  359. }
  360. else
  361. {
  362. rs = instance;
  363. }
  364. }
  365. int sep = Mathf.Max(rs.FindLast("/"), rs.FindLast("\\"));
  366. if (sep == -1)
  367. return @base;
  368. return @base + rs.Substr(0, sep);
  369. }
  370. /// <summary>
  371. /// If the string is a path to a file, return the file and ignore the base directory.
  372. /// </summary>
  373. public static string GetFile(this string instance)
  374. {
  375. int sep = Mathf.Max(instance.FindLast("/"), instance.FindLast("\\"));
  376. if (sep == -1)
  377. return instance;
  378. return instance.Substring(sep + 1);
  379. }
  380. /// <summary>
  381. /// Converts the given byte array of ASCII encoded text to a string.
  382. /// Faster alternative to <see cref="GetStringFromUTF8"/> if the
  383. /// content is ASCII-only. Unlike the UTF-8 function this function
  384. /// maps every byte to a character in the array. Multibyte sequences
  385. /// will not be interpreted correctly. For parsing user input always
  386. /// use <see cref="GetStringFromUTF8"/>.
  387. /// </summary>
  388. /// <param name="bytes">A byte array of ASCII characters (on the range of 0-127).</param>
  389. /// <returns>A string created from the bytes.</returns>
  390. public static string GetStringFromASCII(this byte[] bytes)
  391. {
  392. return Encoding.ASCII.GetString(bytes);
  393. }
  394. /// <summary>
  395. /// Converts the given byte array of UTF-8 encoded text to a string.
  396. /// Slower than <see cref="GetStringFromASCII"/> but supports UTF-8
  397. /// encoded data. Use this function if you are unsure about the
  398. /// source of the data. For user input this function
  399. /// should always be preferred.
  400. /// </summary>
  401. /// <param name="bytes">A byte array of UTF-8 characters (a character may take up multiple bytes).</param>
  402. /// <returns>A string created from the bytes.</returns>
  403. public static string GetStringFromUTF8(this byte[] bytes)
  404. {
  405. return Encoding.UTF8.GetString(bytes);
  406. }
  407. /// <summary>
  408. /// Hash the string and return a 32 bits unsigned integer.
  409. /// </summary>
  410. public static uint Hash(this string instance)
  411. {
  412. uint hash = 5381;
  413. foreach (uint c in instance)
  414. {
  415. hash = (hash << 5) + hash + c; // hash * 33 + c
  416. }
  417. return hash;
  418. }
  419. /// <summary>
  420. /// Returns a hexadecimal representation of this byte as a string.
  421. /// </summary>
  422. /// <param name="b">The byte to encode.</param>
  423. /// <returns>The hexadecimal representation of this byte.</returns>
  424. internal static string HexEncode(this byte b)
  425. {
  426. var ret = string.Empty;
  427. for (int i = 0; i < 2; i++)
  428. {
  429. char c;
  430. int lv = b & 0xF;
  431. if (lv < 10)
  432. {
  433. c = (char)('0' + lv);
  434. }
  435. else
  436. {
  437. c = (char)('a' + lv - 10);
  438. }
  439. b >>= 4;
  440. ret = c + ret;
  441. }
  442. return ret;
  443. }
  444. /// <summary>
  445. /// Returns a hexadecimal representation of this byte array as a string.
  446. /// </summary>
  447. /// <param name="bytes">The byte array to encode.</param>
  448. /// <returns>The hexadecimal representation of this byte array.</returns>
  449. public static string HexEncode(this byte[] bytes)
  450. {
  451. var ret = string.Empty;
  452. foreach (byte b in bytes)
  453. {
  454. ret += b.HexEncode();
  455. }
  456. return ret;
  457. }
  458. /// <summary>
  459. /// Converts a string containing a hexadecimal number into an integer.
  460. /// Hexadecimal strings can either be prefixed with `0x` or not,
  461. /// and they can also start with a `-` before the optional prefix.
  462. /// </summary>
  463. /// <param name="instance">The string to convert.</param>
  464. /// <returns>The converted string.</returns>
  465. public static int HexToInt(this string instance)
  466. {
  467. if (instance.Length == 0)
  468. {
  469. return 0;
  470. }
  471. int sign = 1;
  472. if (instance[0] == '-')
  473. {
  474. sign = -1;
  475. instance = instance.Substring(1);
  476. }
  477. if (instance.StartsWith("0x"))
  478. {
  479. instance = instance.Substring(2);
  480. }
  481. return sign * int.Parse(instance, NumberStyles.HexNumber);
  482. }
  483. /// <summary>
  484. /// Insert a substring at a given position.
  485. /// </summary>
  486. public static string Insert(this string instance, int pos, string what)
  487. {
  488. return instance.Insert(pos, what);
  489. }
  490. /// <summary>
  491. /// If the string is a path to a file or directory, return <see langword="true"/> if the path is absolute.
  492. /// </summary>
  493. public static bool IsAbsolutePath(this string instance)
  494. {
  495. if (string.IsNullOrEmpty(instance))
  496. return false;
  497. else if (instance.Length > 1)
  498. return instance[0] == '/' || instance[0] == '\\' || instance.Contains(":/") || instance.Contains(":\\");
  499. else
  500. return instance[0] == '/' || instance[0] == '\\';
  501. }
  502. /// <summary>
  503. /// If the string is a path to a file or directory, return <see langword="true"/> if the path is relative.
  504. /// </summary>
  505. public static bool IsRelativePath(this string instance)
  506. {
  507. return !IsAbsolutePath(instance);
  508. }
  509. /// <summary>
  510. /// Check whether this string is a subsequence of the given string.
  511. /// </summary>
  512. public static bool IsSubsequenceOf(this string instance, string text, bool caseSensitive = true)
  513. {
  514. int len = instance.Length;
  515. if (len == 0)
  516. return true; // Technically an empty string is subsequence of any string
  517. if (len > text.Length)
  518. return false;
  519. int source = 0;
  520. int target = 0;
  521. while (source < len && target < text.Length)
  522. {
  523. bool match;
  524. if (!caseSensitive)
  525. {
  526. char sourcec = char.ToLower(instance[source]);
  527. char targetc = char.ToLower(text[target]);
  528. match = sourcec == targetc;
  529. }
  530. else
  531. {
  532. match = instance[source] == text[target];
  533. }
  534. if (match)
  535. {
  536. source++;
  537. if (source >= len)
  538. return true;
  539. }
  540. target++;
  541. }
  542. return false;
  543. }
  544. /// <summary>
  545. /// Check whether this string is a subsequence of the given string, ignoring case differences.
  546. /// </summary>
  547. public static bool IsSubsequenceOfI(this string instance, string text)
  548. {
  549. return instance.IsSubsequenceOf(text, caseSensitive: false);
  550. }
  551. /// <summary>
  552. /// Check whether the string contains a valid <see langword="float"/>.
  553. /// </summary>
  554. public static bool IsValidFloat(this string instance)
  555. {
  556. float f;
  557. return float.TryParse(instance, out f);
  558. }
  559. /// <summary>
  560. /// Check whether the string contains a valid color in HTML notation.
  561. /// </summary>
  562. public static bool IsValidHtmlColor(this string instance)
  563. {
  564. return Color.HtmlIsValid(instance);
  565. }
  566. /// <summary>
  567. /// Check whether the string is a valid identifier. As is common in
  568. /// programming languages, a valid identifier may contain only letters,
  569. /// digits and underscores (_) and the first character may not be a digit.
  570. /// </summary>
  571. public static bool IsValidIdentifier(this string instance)
  572. {
  573. int len = instance.Length;
  574. if (len == 0)
  575. return false;
  576. for (int i = 0; i < len; i++)
  577. {
  578. if (i == 0)
  579. {
  580. if (instance[0] >= '0' && instance[0] <= '9')
  581. return false; // Don't start with number plz
  582. }
  583. bool validChar = instance[i] >= '0' &&
  584. instance[i] <= '9' || instance[i] >= 'a' &&
  585. instance[i] <= 'z' || instance[i] >= 'A' &&
  586. instance[i] <= 'Z' || instance[i] == '_';
  587. if (!validChar)
  588. return false;
  589. }
  590. return true;
  591. }
  592. /// <summary>
  593. /// Check whether the string contains a valid integer.
  594. /// </summary>
  595. public static bool IsValidInteger(this string instance)
  596. {
  597. int f;
  598. return int.TryParse(instance, out f);
  599. }
  600. /// <summary>
  601. /// Check whether the string contains a valid IP address.
  602. /// </summary>
  603. public static bool IsValidIPAddress(this string instance)
  604. {
  605. // TODO: Support IPv6 addresses
  606. string[] ip = instance.Split(".");
  607. if (ip.Length != 4)
  608. return false;
  609. for (int i = 0; i < ip.Length; i++)
  610. {
  611. string n = ip[i];
  612. if (!n.IsValidInteger())
  613. return false;
  614. int val = n.ToInt();
  615. if (val < 0 || val > 255)
  616. return false;
  617. }
  618. return true;
  619. }
  620. /// <summary>
  621. /// Return a copy of the string with special characters escaped using the JSON standard.
  622. /// </summary>
  623. public static string JSONEscape(this string instance)
  624. {
  625. var sb = new StringBuilder(string.Copy(instance));
  626. sb.Replace("\\", "\\\\");
  627. sb.Replace("\b", "\\b");
  628. sb.Replace("\f", "\\f");
  629. sb.Replace("\n", "\\n");
  630. sb.Replace("\r", "\\r");
  631. sb.Replace("\t", "\\t");
  632. sb.Replace("\v", "\\v");
  633. sb.Replace("\"", "\\\"");
  634. return sb.ToString();
  635. }
  636. /// <summary>
  637. /// Return an amount of characters from the left of the string.
  638. /// </summary>
  639. public static string Left(this string instance, int pos)
  640. {
  641. if (pos <= 0)
  642. return string.Empty;
  643. if (pos >= instance.Length)
  644. return instance;
  645. return instance.Substring(0, pos);
  646. }
  647. /// <summary>
  648. /// Return the length of the string in characters.
  649. /// </summary>
  650. public static int Length(this string instance)
  651. {
  652. return instance.Length;
  653. }
  654. /// <summary>
  655. /// Returns a copy of the string with characters removed from the left.
  656. /// </summary>
  657. /// <param name="instance">The string to remove characters from.</param>
  658. /// <param name="chars">The characters to be removed.</param>
  659. /// <returns>A copy of the string with characters removed from the left.</returns>
  660. public static string LStrip(this string instance, string chars)
  661. {
  662. int len = instance.Length;
  663. int beg;
  664. for (beg = 0; beg < len; beg++)
  665. {
  666. if (chars.Find(instance[beg]) == -1)
  667. {
  668. break;
  669. }
  670. }
  671. if (beg == 0)
  672. {
  673. return instance;
  674. }
  675. return instance.Substr(beg, len - beg);
  676. }
  677. /// <summary>
  678. /// Do a simple expression match, where '*' matches zero or more
  679. /// arbitrary characters and '?' matches any single character except '.'.
  680. /// </summary>
  681. private static bool ExprMatch(this string instance, string expr, bool caseSensitive)
  682. {
  683. // case '\0':
  684. if (expr.Length == 0)
  685. return instance.Length == 0;
  686. switch (expr[0])
  687. {
  688. case '*':
  689. return ExprMatch(instance, expr.Substring(1), caseSensitive) || (instance.Length > 0 && ExprMatch(instance.Substring(1), expr, caseSensitive));
  690. case '?':
  691. return instance.Length > 0 && instance[0] != '.' && ExprMatch(instance.Substring(1), expr.Substring(1), caseSensitive);
  692. default:
  693. if (instance.Length == 0)
  694. return false;
  695. if (caseSensitive)
  696. return instance[0] == expr[0];
  697. return (char.ToUpper(instance[0]) == char.ToUpper(expr[0])) && ExprMatch(instance.Substring(1), expr.Substring(1), caseSensitive);
  698. }
  699. }
  700. /// <summary>
  701. /// Do a simple case sensitive expression match, using ? and * wildcards
  702. /// (see <see cref="ExprMatch(string, string, bool)"/>).
  703. /// </summary>
  704. public static bool Match(this string instance, string expr, bool caseSensitive = true)
  705. {
  706. if (instance.Length == 0 || expr.Length == 0)
  707. return false;
  708. return instance.ExprMatch(expr, caseSensitive);
  709. }
  710. /// <summary>
  711. /// Do a simple case insensitive expression match, using ? and * wildcards
  712. /// (see <see cref="ExprMatch(string, string, bool)"/>).
  713. /// </summary>
  714. public static bool MatchN(this string instance, string expr)
  715. {
  716. if (instance.Length == 0 || expr.Length == 0)
  717. return false;
  718. return instance.ExprMatch(expr, caseSensitive: false);
  719. }
  720. /// <summary>
  721. /// Return the MD5 hash of the string as an array of bytes.
  722. /// </summary>
  723. public static byte[] MD5Buffer(this string instance)
  724. {
  725. return godot_icall_String_md5_buffer(instance);
  726. }
  727. [MethodImpl(MethodImplOptions.InternalCall)]
  728. internal extern static byte[] godot_icall_String_md5_buffer(string str);
  729. /// <summary>
  730. /// Return the MD5 hash of the string as a string.
  731. /// </summary>
  732. public static string MD5Text(this string instance)
  733. {
  734. return godot_icall_String_md5_text(instance);
  735. }
  736. [MethodImpl(MethodImplOptions.InternalCall)]
  737. internal extern static string godot_icall_String_md5_text(string str);
  738. /// <summary>
  739. /// Perform a case-insensitive comparison to another string, return -1 if less, 0 if equal and +1 if greater.
  740. /// </summary>
  741. public static int NocasecmpTo(this string instance, string to)
  742. {
  743. return instance.CompareTo(to, caseSensitive: false);
  744. }
  745. /// <summary>
  746. /// Return the character code at position <paramref name="at"/>.
  747. /// </summary>
  748. public static int OrdAt(this string instance, int at)
  749. {
  750. return instance[at];
  751. }
  752. /// <summary>
  753. /// Format a number to have an exact number of <paramref name="digits"/> after the decimal point.
  754. /// </summary>
  755. public static string PadDecimals(this string instance, int digits)
  756. {
  757. int c = instance.Find(".");
  758. if (c == -1)
  759. {
  760. if (digits <= 0)
  761. return instance;
  762. instance += ".";
  763. c = instance.Length - 1;
  764. }
  765. else
  766. {
  767. if (digits <= 0)
  768. return instance.Substring(0, c);
  769. }
  770. if (instance.Length - (c + 1) > digits)
  771. {
  772. instance = instance.Substring(0, c + digits + 1);
  773. }
  774. else
  775. {
  776. while (instance.Length - (c + 1) < digits)
  777. {
  778. instance += "0";
  779. }
  780. }
  781. return instance;
  782. }
  783. /// <summary>
  784. /// Format a number to have an exact number of <paramref name="digits"/> before the decimal point.
  785. /// </summary>
  786. public static string PadZeros(this string instance, int digits)
  787. {
  788. string s = instance;
  789. int end = s.Find(".");
  790. if (end == -1)
  791. end = s.Length;
  792. if (end == 0)
  793. return s;
  794. int begin = 0;
  795. while (begin < end && (s[begin] < '0' || s[begin] > '9'))
  796. {
  797. begin++;
  798. }
  799. if (begin >= end)
  800. return s;
  801. while (end - begin < digits)
  802. {
  803. s = s.Insert(begin, "0");
  804. end++;
  805. }
  806. return s;
  807. }
  808. /// <summary>
  809. /// If the string is a path, this concatenates <paramref name="file"/> at the end of the string as a subpath.
  810. /// E.g. <c>"this/is".PlusFile("path") == "this/is/path"</c>.
  811. /// </summary>
  812. public static string PlusFile(this string instance, string file)
  813. {
  814. if (instance.Length > 0 && instance[instance.Length - 1] == '/')
  815. return instance + file;
  816. return instance + "/" + file;
  817. }
  818. /// <summary>
  819. /// Replace occurrences of a substring for different ones inside the string.
  820. /// </summary>
  821. public static string Replace(this string instance, string what, string forwhat)
  822. {
  823. return instance.Replace(what, forwhat);
  824. }
  825. /// <summary>
  826. /// Replace occurrences of a substring for different ones inside the string, but search case-insensitive.
  827. /// </summary>
  828. public static string ReplaceN(this string instance, string what, string forwhat)
  829. {
  830. return Regex.Replace(instance, what, forwhat, RegexOptions.IgnoreCase);
  831. }
  832. /// <summary>
  833. /// Perform a search for a substring, but start from the end of the string instead of the beginning.
  834. /// </summary>
  835. public static int RFind(this string instance, string what, int from = -1)
  836. {
  837. return godot_icall_String_rfind(instance, what, from);
  838. }
  839. [MethodImpl(MethodImplOptions.InternalCall)]
  840. internal extern static int godot_icall_String_rfind(string str, string what, int from);
  841. /// <summary>
  842. /// Perform a search for a substring, but start from the end of the string instead of the beginning.
  843. /// Also search case-insensitive.
  844. /// </summary>
  845. public static int RFindN(this string instance, string what, int from = -1)
  846. {
  847. return godot_icall_String_rfindn(instance, what, from);
  848. }
  849. [MethodImpl(MethodImplOptions.InternalCall)]
  850. internal extern static int godot_icall_String_rfindn(string str, string what, int from);
  851. /// <summary>
  852. /// Return the right side of the string from a given position.
  853. /// </summary>
  854. public static string Right(this string instance, int pos)
  855. {
  856. if (pos >= instance.Length)
  857. return instance;
  858. if (pos < 0)
  859. return string.Empty;
  860. return instance.Substring(pos, instance.Length - pos);
  861. }
  862. /// <summary>
  863. /// Returns a copy of the string with characters removed from the right.
  864. /// </summary>
  865. /// <param name="instance">The string to remove characters from.</param>
  866. /// <param name="chars">The characters to be removed.</param>
  867. /// <returns>A copy of the string with characters removed from the right.</returns>
  868. public static string RStrip(this string instance, string chars)
  869. {
  870. int len = instance.Length;
  871. int end;
  872. for (end = len - 1; end >= 0; end--)
  873. {
  874. if (chars.Find(instance[end]) == -1)
  875. {
  876. break;
  877. }
  878. }
  879. if (end == len - 1)
  880. {
  881. return instance;
  882. }
  883. return instance.Substr(0, end + 1);
  884. }
  885. public static byte[] SHA256Buffer(this string instance)
  886. {
  887. return godot_icall_String_sha256_buffer(instance);
  888. }
  889. [MethodImpl(MethodImplOptions.InternalCall)]
  890. internal extern static byte[] godot_icall_String_sha256_buffer(string str);
  891. /// <summary>
  892. /// Return the SHA-256 hash of the string as a string.
  893. /// </summary>
  894. public static string SHA256Text(this string instance)
  895. {
  896. return godot_icall_String_sha256_text(instance);
  897. }
  898. [MethodImpl(MethodImplOptions.InternalCall)]
  899. internal extern static string godot_icall_String_sha256_text(string str);
  900. /// <summary>
  901. /// Return the similarity index of the text compared to this string.
  902. /// 1 means totally similar and 0 means totally dissimilar.
  903. /// </summary>
  904. public static float Similarity(this string instance, string text)
  905. {
  906. if (instance == text)
  907. {
  908. // Equal strings are totally similar
  909. return 1.0f;
  910. }
  911. if (instance.Length < 2 || text.Length < 2)
  912. {
  913. // No way to calculate similarity without a single bigram
  914. return 0.0f;
  915. }
  916. string[] sourceBigrams = instance.Bigrams();
  917. string[] targetBigrams = text.Bigrams();
  918. int sourceSize = sourceBigrams.Length;
  919. int targetSize = targetBigrams.Length;
  920. float sum = sourceSize + targetSize;
  921. float inter = 0;
  922. for (int i = 0; i < sourceSize; i++)
  923. {
  924. for (int j = 0; j < targetSize; j++)
  925. {
  926. if (sourceBigrams[i] == targetBigrams[j])
  927. {
  928. inter++;
  929. break;
  930. }
  931. }
  932. }
  933. return 2.0f * inter / sum;
  934. }
  935. /// <summary>
  936. /// Returns a simplified canonical path.
  937. /// </summary>
  938. public static string SimplifyPath(this string instance)
  939. {
  940. return godot_icall_String_simplify_path(instance);
  941. }
  942. [MethodImpl(MethodImplOptions.InternalCall)]
  943. internal extern static string godot_icall_String_simplify_path(string str);
  944. /// <summary>
  945. /// Split the string by a divisor string, return an array of the substrings.
  946. /// Example "One,Two,Three" will return ["One","Two","Three"] if split by ",".
  947. /// </summary>
  948. public static string[] Split(this string instance, string divisor, bool allowEmpty = true)
  949. {
  950. return instance.Split(new[] { divisor }, allowEmpty ? StringSplitOptions.None : StringSplitOptions.RemoveEmptyEntries);
  951. }
  952. /// <summary>
  953. /// Split the string in floats by using a divisor string, return an array of the substrings.
  954. /// Example "1,2.5,3" will return [1,2.5,3] if split by ",".
  955. /// </summary>
  956. public static float[] SplitFloats(this string instance, string divisor, bool allowEmpty = true)
  957. {
  958. var ret = new List<float>();
  959. int from = 0;
  960. int len = instance.Length;
  961. while (true)
  962. {
  963. int end = instance.Find(divisor, from, caseSensitive: true);
  964. if (end < 0)
  965. end = len;
  966. if (allowEmpty || end > from)
  967. ret.Add(float.Parse(instance.Substring(from)));
  968. if (end == len)
  969. break;
  970. from = end + divisor.Length;
  971. }
  972. return ret.ToArray();
  973. }
  974. private static readonly char[] _nonPrintable = {
  975. (char)00, (char)01, (char)02, (char)03, (char)04, (char)05,
  976. (char)06, (char)07, (char)08, (char)09, (char)10, (char)11,
  977. (char)12, (char)13, (char)14, (char)15, (char)16, (char)17,
  978. (char)18, (char)19, (char)20, (char)21, (char)22, (char)23,
  979. (char)24, (char)25, (char)26, (char)27, (char)28, (char)29,
  980. (char)30, (char)31, (char)32
  981. };
  982. /// <summary>
  983. /// Return a copy of the string stripped of any non-printable character at the beginning and the end.
  984. /// The optional arguments are used to toggle stripping on the left and right edges respectively.
  985. /// </summary>
  986. public static string StripEdges(this string instance, bool left = true, bool right = true)
  987. {
  988. if (left)
  989. {
  990. if (right)
  991. return instance.Trim(_nonPrintable);
  992. return instance.TrimStart(_nonPrintable);
  993. }
  994. return instance.TrimEnd(_nonPrintable);
  995. }
  996. /// <summary>
  997. /// Return part of the string from the position <paramref name="from"/>, with length <paramref name="len"/>.
  998. /// </summary>
  999. public static string Substr(this string instance, int from, int len)
  1000. {
  1001. int max = instance.Length - from;
  1002. return instance.Substring(from, len > max ? max : len);
  1003. }
  1004. /// <summary>
  1005. /// Convert the String (which is a character array) to PackedByteArray (which is an array of bytes).
  1006. /// The conversion is speeded up in comparison to <see cref="ToUTF8(string)"/> with the assumption
  1007. /// that all the characters the String contains are only ASCII characters.
  1008. /// </summary>
  1009. public static byte[] ToAscii(this string instance)
  1010. {
  1011. return Encoding.ASCII.GetBytes(instance);
  1012. }
  1013. /// <summary>
  1014. /// Convert a string, containing a decimal number, into a <see langword="float" />.
  1015. /// </summary>
  1016. public static float ToFloat(this string instance)
  1017. {
  1018. return float.Parse(instance);
  1019. }
  1020. /// <summary>
  1021. /// Convert a string, containing an integer number, into an <see langword="int" />.
  1022. /// </summary>
  1023. public static int ToInt(this string instance)
  1024. {
  1025. return int.Parse(instance);
  1026. }
  1027. /// <summary>
  1028. /// Return the string converted to lowercase.
  1029. /// </summary>
  1030. public static string ToLower(this string instance)
  1031. {
  1032. return instance.ToLower();
  1033. }
  1034. /// <summary>
  1035. /// Return the string converted to uppercase.
  1036. /// </summary>
  1037. public static string ToUpper(this string instance)
  1038. {
  1039. return instance.ToUpper();
  1040. }
  1041. /// <summary>
  1042. /// Convert the String (which is an array of characters) to PackedByteArray (which is an array of bytes).
  1043. /// The conversion is a bit slower than <see cref="ToAscii(string)"/>, but supports all UTF-8 characters.
  1044. /// Therefore, you should prefer this function over <see cref="ToAscii(string)"/>.
  1045. /// </summary>
  1046. public static byte[] ToUTF8(this string instance)
  1047. {
  1048. return Encoding.UTF8.GetBytes(instance);
  1049. }
  1050. /// <summary>
  1051. /// Decodes a string in URL encoded format. This is meant to
  1052. /// decode parameters in a URL when receiving an HTTP request.
  1053. /// This mostly wraps around `System.Uri.UnescapeDataString()`,
  1054. /// but also handles `+`.
  1055. /// See <see cref="URIEncode"/> for encoding.
  1056. /// </summary>
  1057. /// <param name="instance">The string to decode.</param>
  1058. /// <returns>The unescaped string.</returns>
  1059. public static string URIDecode(this string instance)
  1060. {
  1061. return Uri.UnescapeDataString(instance.Replace("+", "%20"));
  1062. }
  1063. /// <summary>
  1064. /// Encodes a string to URL friendly format. This is meant to
  1065. /// encode parameters in a URL when sending an HTTP request.
  1066. /// This wraps around `System.Uri.EscapeDataString()`.
  1067. /// See <see cref="URIDecode"/> for decoding.
  1068. /// </summary>
  1069. /// <param name="instance">The string to encode.</param>
  1070. /// <returns>The escaped string.</returns>
  1071. public static string URIEncode(this string instance)
  1072. {
  1073. return Uri.EscapeDataString(instance);
  1074. }
  1075. /// <summary>
  1076. /// Return a copy of the string with special characters escaped using the XML standard.
  1077. /// </summary>
  1078. public static string XMLEscape(this string instance)
  1079. {
  1080. return SecurityElement.Escape(instance);
  1081. }
  1082. /// <summary>
  1083. /// Return a copy of the string with escaped characters replaced by their meanings
  1084. /// according to the XML standard.
  1085. /// </summary>
  1086. public static string XMLUnescape(this string instance)
  1087. {
  1088. return SecurityElement.FromString(instance).Text;
  1089. }
  1090. }
  1091. }