StringExtensions.cs 42 KB

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