StringExtensions.cs 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Globalization;
  4. using System.Security;
  5. using System.Text;
  6. using System.Text.RegularExpressions;
  7. namespace Godot
  8. {
  9. public static class StringExtensions
  10. {
  11. private static int GetSliceCount(this string instance, string splitter)
  12. {
  13. if (instance.Empty() || splitter.Empty())
  14. return 0;
  15. int pos = 0;
  16. int slices = 1;
  17. while ((pos = instance.Find(splitter, pos)) >= 0)
  18. {
  19. slices++;
  20. pos += splitter.Length;
  21. }
  22. return slices;
  23. }
  24. private static string GetSliceCharacter(this string instance, char splitter, int slice)
  25. {
  26. if (!instance.Empty() && slice >= 0)
  27. {
  28. int i = 0;
  29. int prev = 0;
  30. int count = 0;
  31. while (true)
  32. {
  33. bool end = instance.Length <= i;
  34. if (end || instance[i] == splitter)
  35. {
  36. if (slice == count)
  37. {
  38. return instance.Substring(prev, i - prev);
  39. }
  40. else if (end)
  41. {
  42. return string.Empty;
  43. }
  44. count++;
  45. prev = i + 1;
  46. }
  47. i++;
  48. }
  49. }
  50. return string.Empty;
  51. }
  52. // <summary>
  53. // If the string is a path to a file, return the path to the file without the extension.
  54. // </summary>
  55. public static string BaseName(this string instance)
  56. {
  57. int index = instance.LastIndexOf('.');
  58. if (index > 0)
  59. return instance.Substring(0, index);
  60. return instance;
  61. }
  62. // <summary>
  63. // Return true if the strings begins with the given string.
  64. // </summary>
  65. public static bool BeginsWith(this string instance, string text)
  66. {
  67. return instance.StartsWith(text);
  68. }
  69. // <summary>
  70. // Return the bigrams (pairs of consecutive letters) of this string.
  71. // </summary>
  72. public static string[] Bigrams(this string instance)
  73. {
  74. var b = new string[instance.Length - 1];
  75. for (int i = 0; i < b.Length; i++)
  76. {
  77. b[i] = instance.Substring(i, 2);
  78. }
  79. return b;
  80. }
  81. // <summary>
  82. // Return a copy of the string with special characters escaped using the C language standard.
  83. // </summary>
  84. public static string CEscape(this string instance)
  85. {
  86. var sb = new StringBuilder(string.Copy(instance));
  87. sb.Replace("\\", "\\\\");
  88. sb.Replace("\a", "\\a");
  89. sb.Replace("\b", "\\b");
  90. sb.Replace("\f", "\\f");
  91. sb.Replace("\n", "\\n");
  92. sb.Replace("\r", "\\r");
  93. sb.Replace("\t", "\\t");
  94. sb.Replace("\v", "\\v");
  95. sb.Replace("\'", "\\'");
  96. sb.Replace("\"", "\\\"");
  97. sb.Replace("?", "\\?");
  98. return sb.ToString();
  99. }
  100. // <summary>
  101. // Return a copy of the string with escaped characters replaced by their meanings according to the C language standard.
  102. // </summary>
  103. public static string CUnescape(this string instance)
  104. {
  105. var sb = new StringBuilder(string.Copy(instance));
  106. sb.Replace("\\a", "\a");
  107. sb.Replace("\\b", "\b");
  108. sb.Replace("\\f", "\f");
  109. sb.Replace("\\n", "\n");
  110. sb.Replace("\\r", "\r");
  111. sb.Replace("\\t", "\t");
  112. sb.Replace("\\v", "\v");
  113. sb.Replace("\\'", "\'");
  114. sb.Replace("\\\"", "\"");
  115. sb.Replace("\\?", "?");
  116. sb.Replace("\\\\", "\\");
  117. return sb.ToString();
  118. }
  119. // <summary>
  120. // 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].
  121. // </summary>
  122. public static string Capitalize(this string instance)
  123. {
  124. string aux = instance.Replace("_", " ").ToLower();
  125. var cap = string.Empty;
  126. for (int i = 0; i < aux.GetSliceCount(" "); i++)
  127. {
  128. string slice = aux.GetSliceCharacter(' ', i);
  129. if (slice.Length > 0)
  130. {
  131. slice = char.ToUpper(slice[0]) + slice.Substring(1);
  132. if (i > 0)
  133. cap += " ";
  134. cap += slice;
  135. }
  136. }
  137. return cap;
  138. }
  139. // <summary>
  140. // Perform a case-sensitive comparison to another string, return -1 if less, 0 if equal and +1 if greater.
  141. // </summary>
  142. public static int CasecmpTo(this string instance, string to)
  143. {
  144. return instance.CompareTo(to, true);
  145. }
  146. // <summary>
  147. // Perform a comparison to another string, return -1 if less, 0 if equal and +1 if greater.
  148. // </summary>
  149. public static int CompareTo(this string instance, string to, bool caseSensitive = true)
  150. {
  151. if (instance.Empty())
  152. return to.Empty() ? 0 : -1;
  153. if (to.Empty())
  154. return 1;
  155. int instanceIndex = 0;
  156. int toIndex = 0;
  157. if (caseSensitive) // Outside while loop to avoid checking multiple times, despite some code duplication.
  158. {
  159. while (true)
  160. {
  161. if (to[toIndex] == 0 && instance[instanceIndex] == 0)
  162. return 0; // We're equal
  163. if (instance[instanceIndex] == 0)
  164. return -1; // If this is empty, and the other one is not, then we're less... I think?
  165. if (to[toIndex] == 0)
  166. return 1; // Otherwise the other one is smaller...
  167. if (instance[instanceIndex] < to[toIndex]) // More than
  168. return -1;
  169. if (instance[instanceIndex] > to[toIndex]) // Less than
  170. return 1;
  171. instanceIndex++;
  172. toIndex++;
  173. }
  174. } else
  175. {
  176. while (true)
  177. {
  178. if (to[toIndex] == 0 && instance[instanceIndex] == 0)
  179. return 0; // We're equal
  180. if (instance[instanceIndex] == 0)
  181. return -1; // If this is empty, and the other one is not, then we're less... I think?
  182. if (to[toIndex] == 0)
  183. return 1; // Otherwise the other one is smaller..
  184. if (char.ToUpper(instance[instanceIndex]) < char.ToUpper(to[toIndex])) // More than
  185. return -1;
  186. if (char.ToUpper(instance[instanceIndex]) > char.ToUpper(to[toIndex])) // Less than
  187. return 1;
  188. instanceIndex++;
  189. toIndex++;
  190. }
  191. }
  192. }
  193. // <summary>
  194. // Return true if the string is empty.
  195. // </summary>
  196. public static bool Empty(this string instance)
  197. {
  198. return string.IsNullOrEmpty(instance);
  199. }
  200. // <summary>
  201. // Return true if the strings ends with the given string.
  202. // </summary>
  203. public static bool EndsWith(this string instance, string text)
  204. {
  205. return instance.EndsWith(text);
  206. }
  207. // <summary>
  208. // Erase [code]chars[/code] characters from the string starting from [code]pos[/code].
  209. // </summary>
  210. public static void Erase(this StringBuilder instance, int pos, int chars)
  211. {
  212. instance.Remove(pos, chars);
  213. }
  214. // <summary>
  215. // If the string is a path to a file, return the extension.
  216. // </summary>
  217. public static string Extension(this string instance)
  218. {
  219. int pos = instance.FindLast(".");
  220. if (pos < 0)
  221. return instance;
  222. return instance.Substring(pos + 1);
  223. }
  224. // <summary>
  225. // Find the first occurrence of a substring, return the starting position of the substring or -1 if not found. Optionally, the initial search index can be passed.
  226. // </summary>
  227. public static int Find(this string instance, string what, int from = 0)
  228. {
  229. return instance.IndexOf(what, StringComparison.OrdinalIgnoreCase);
  230. }
  231. // <summary>
  232. // Find the last occurrence of a substring, return the starting position of the substring or -1 if not found. Optionally, the initial search index can be passed.
  233. // </summary>
  234. public static int FindLast(this string instance, string what)
  235. {
  236. return instance.LastIndexOf(what, StringComparison.OrdinalIgnoreCase);
  237. }
  238. // <summary>
  239. // Find the first occurrence of a substring but search as case-insensitive, return the starting position of the substring or -1 if not found. Optionally, the initial search index can be passed.
  240. // </summary>
  241. public static int FindN(this string instance, string what, int from = 0)
  242. {
  243. return instance.IndexOf(what, StringComparison.Ordinal);
  244. }
  245. // <summary>
  246. // If the string is a path to a file, return the base directory.
  247. // </summary>
  248. public static string GetBaseDir(this string instance)
  249. {
  250. int basepos = instance.Find("://");
  251. string rs;
  252. var @base = string.Empty;
  253. if (basepos != -1)
  254. {
  255. var end = basepos + 3;
  256. rs = instance.Substring(end, instance.Length);
  257. @base = instance.Substring(0, end);
  258. }
  259. else
  260. {
  261. if (instance.BeginsWith("/"))
  262. {
  263. rs = instance.Substring(1, instance.Length);
  264. @base = "/";
  265. }
  266. else
  267. {
  268. rs = instance;
  269. }
  270. }
  271. int sep = Mathf.Max(rs.FindLast("/"), rs.FindLast("\\"));
  272. if (sep == -1)
  273. return @base;
  274. return @base + rs.Substr(0, sep);
  275. }
  276. // <summary>
  277. // If the string is a path to a file, return the file and ignore the base directory.
  278. // </summary>
  279. public static string GetFile(this string instance)
  280. {
  281. int sep = Mathf.Max(instance.FindLast("/"), instance.FindLast("\\"));
  282. if (sep == -1)
  283. return instance;
  284. return instance.Substring(sep + 1, instance.Length);
  285. }
  286. // <summary>
  287. // Hash the string and return a 32 bits integer.
  288. // </summary>
  289. public static int Hash(this string instance)
  290. {
  291. int index = 0;
  292. int hashv = 5381;
  293. int c;
  294. while ((c = instance[index++]) != 0)
  295. hashv = (hashv << 5) + hashv + c; // hash * 33 + c
  296. return hashv;
  297. }
  298. // <summary>
  299. // Convert a string containing an hexadecimal number into an int.
  300. // </summary>
  301. public static int HexToInt(this string instance)
  302. {
  303. int sign = 1;
  304. if (instance[0] == '-')
  305. {
  306. sign = -1;
  307. instance = instance.Substring(1);
  308. }
  309. if (!instance.StartsWith("0x"))
  310. return 0;
  311. return sign * int.Parse(instance.Substring(2), NumberStyles.HexNumber);
  312. }
  313. // <summary>
  314. // Insert a substring at a given position.
  315. // </summary>
  316. public static string Insert(this string instance, int pos, string what)
  317. {
  318. return instance.Insert(pos, what);
  319. }
  320. // <summary>
  321. // If the string is a path to a file or directory, return true if the path is absolute.
  322. // </summary>
  323. public static bool IsAbsPath(this string instance)
  324. {
  325. return System.IO.Path.IsPathRooted(instance);
  326. }
  327. // <summary>
  328. // If the string is a path to a file or directory, return true if the path is relative.
  329. // </summary>
  330. public static bool IsRelPath(this string instance)
  331. {
  332. return !System.IO.Path.IsPathRooted(instance);
  333. }
  334. // <summary>
  335. // Check whether this string is a subsequence of the given string.
  336. // </summary>
  337. public static bool IsSubsequenceOf(this string instance, string text, bool caseSensitive = true)
  338. {
  339. int len = instance.Length;
  340. if (len == 0)
  341. return true; // Technically an empty string is subsequence of any string
  342. if (len > text.Length)
  343. return false;
  344. int source = 0;
  345. int target = 0;
  346. while (instance[source] != 0 && text[target] != 0)
  347. {
  348. bool match;
  349. if (!caseSensitive)
  350. {
  351. char sourcec = char.ToLower(instance[source]);
  352. char targetc = char.ToLower(text[target]);
  353. match = sourcec == targetc;
  354. }
  355. else
  356. {
  357. match = instance[source] == text[target];
  358. }
  359. if (match)
  360. {
  361. source++;
  362. if (instance[source] == 0)
  363. return true;
  364. }
  365. target++;
  366. }
  367. return false;
  368. }
  369. // <summary>
  370. // Check whether this string is a subsequence of the given string, ignoring case differences.
  371. // </summary>
  372. public static bool IsSubsequenceOfI(this string instance, string text)
  373. {
  374. return instance.IsSubsequenceOf(text, false);
  375. }
  376. // <summary>
  377. // Check whether the string contains a valid float.
  378. // </summary>
  379. public static bool IsValidFloat(this string instance)
  380. {
  381. float f;
  382. return float.TryParse(instance, out f);
  383. }
  384. // <summary>
  385. // Check whether the string contains a valid color in HTML notation.
  386. // </summary>
  387. public static bool IsValidHtmlColor(this string instance)
  388. {
  389. return Color.HtmlIsValid(instance);
  390. }
  391. // <summary>
  392. // 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.
  393. // </summary>
  394. public static bool IsValidIdentifier(this string instance)
  395. {
  396. int len = instance.Length;
  397. if (len == 0)
  398. return false;
  399. for (int i = 0; i < len; i++)
  400. {
  401. if (i == 0)
  402. {
  403. if (instance[0] >= '0' && instance[0] <= '9')
  404. return false; // Don't start with number plz
  405. }
  406. bool validChar = instance[i] >= '0' &&
  407. instance[i] <= '9' || instance[i] >= 'a' &&
  408. instance[i] <= 'z' || instance[i] >= 'A' &&
  409. instance[i] <= 'Z' || instance[i] == '_';
  410. if (!validChar)
  411. return false;
  412. }
  413. return true;
  414. }
  415. // <summary>
  416. // Check whether the string contains a valid integer.
  417. // </summary>
  418. public static bool IsValidInteger(this string instance)
  419. {
  420. int f;
  421. return int.TryParse(instance, out f);
  422. }
  423. // <summary>
  424. // Check whether the string contains a valid IP address.
  425. // </summary>
  426. public static bool IsValidIPAddress(this string instance)
  427. {
  428. // TODO: Support IPv6 addresses
  429. string[] ip = instance.Split(".");
  430. if (ip.Length != 4)
  431. return false;
  432. for (int i = 0; i < ip.Length; i++)
  433. {
  434. string n = ip[i];
  435. if (!n.IsValidInteger())
  436. return false;
  437. int val = n.ToInt();
  438. if (val < 0 || val > 255)
  439. return false;
  440. }
  441. return true;
  442. }
  443. // <summary>
  444. // Return a copy of the string with special characters escaped using the JSON standard.
  445. // </summary>
  446. public static string JSONEscape(this string instance)
  447. {
  448. var sb = new StringBuilder(string.Copy(instance));
  449. sb.Replace("\\", "\\\\");
  450. sb.Replace("\b", "\\b");
  451. sb.Replace("\f", "\\f");
  452. sb.Replace("\n", "\\n");
  453. sb.Replace("\r", "\\r");
  454. sb.Replace("\t", "\\t");
  455. sb.Replace("\v", "\\v");
  456. sb.Replace("\"", "\\\"");
  457. return sb.ToString();
  458. }
  459. // <summary>
  460. // Return an amount of characters from the left of the string.
  461. // </summary>
  462. public static string Left(this string instance, int pos)
  463. {
  464. if (pos <= 0)
  465. return string.Empty;
  466. if (pos >= instance.Length)
  467. return instance;
  468. return instance.Substring(0, pos);
  469. }
  470. /// <summary>
  471. /// Return the length of the string in characters.
  472. /// </summary>
  473. public static int Length(this string instance)
  474. {
  475. return instance.Length;
  476. }
  477. // <summary>
  478. // Do a simple expression match, where '*' matches zero or more arbitrary characters and '?' matches any single character except '.'.
  479. // </summary>
  480. public static bool ExprMatch(this string instance, string expr, bool caseSensitive)
  481. {
  482. if (expr.Length == 0 || instance.Length == 0)
  483. return false;
  484. switch (expr[0])
  485. {
  486. case '\0':
  487. return instance[0] == 0;
  488. case '*':
  489. return ExprMatch(expr + 1, instance, caseSensitive) || instance[0] != 0 && ExprMatch(expr, instance + 1, caseSensitive);
  490. case '?':
  491. return instance[0] != 0 && instance[0] != '.' && ExprMatch(expr + 1, instance + 1, caseSensitive);
  492. default:
  493. return (caseSensitive ? instance[0] == expr[0] : char.ToUpper(instance[0]) == char.ToUpper(expr[0])) &&
  494. ExprMatch(expr + 1, instance + 1, caseSensitive);
  495. }
  496. }
  497. // <summary>
  498. // Do a simple case sensitive expression match, using ? and * wildcards (see [method expr_match]).
  499. // </summary>
  500. public static bool Match(this string instance, string expr, bool caseSensitive = true)
  501. {
  502. return instance.ExprMatch(expr, caseSensitive);
  503. }
  504. // <summary>
  505. // Do a simple case insensitive expression match, using ? and * wildcards (see [method expr_match]).
  506. // </summary>
  507. public static bool MatchN(this string instance, string expr)
  508. {
  509. return instance.ExprMatch(expr, false);
  510. }
  511. // <summary>
  512. // Return the MD5 hash of the string as an array of bytes.
  513. // </summary>
  514. public static byte[] MD5Buffer(this string instance)
  515. {
  516. return NativeCalls.godot_icall_String_md5_buffer(instance);
  517. }
  518. // <summary>
  519. // Return the MD5 hash of the string as a string.
  520. // </summary>
  521. public static string MD5Text(this string instance)
  522. {
  523. return NativeCalls.godot_icall_String_md5_text(instance);
  524. }
  525. // <summary>
  526. // Perform a case-insensitive comparison to another string, return -1 if less, 0 if equal and +1 if greater.
  527. // </summary>
  528. public static int NocasecmpTo(this string instance, string to)
  529. {
  530. return instance.CompareTo(to, false);
  531. }
  532. // <summary>
  533. // Return the character code at position [code]at[/code].
  534. // </summary>
  535. public static int OrdAt(this string instance, int at)
  536. {
  537. return instance[at];
  538. }
  539. // <summary>
  540. // Format a number to have an exact number of [code]digits[/code] after the decimal point.
  541. // </summary>
  542. public static string PadDecimals(this string instance, int digits)
  543. {
  544. int c = instance.Find(".");
  545. if (c == -1)
  546. {
  547. if (digits <= 0)
  548. return instance;
  549. instance += ".";
  550. c = instance.Length - 1;
  551. }
  552. else
  553. {
  554. if (digits <= 0)
  555. return instance.Substring(0, c);
  556. }
  557. if (instance.Length - (c + 1) > digits)
  558. {
  559. instance = instance.Substring(0, c + digits + 1);
  560. }
  561. else
  562. {
  563. while (instance.Length - (c + 1) < digits)
  564. {
  565. instance += "0";
  566. }
  567. }
  568. return instance;
  569. }
  570. // <summary>
  571. // Format a number to have an exact number of [code]digits[/code] before the decimal point.
  572. // </summary>
  573. public static string PadZeros(this string instance, int digits)
  574. {
  575. string s = instance;
  576. int end = s.Find(".");
  577. if (end == -1)
  578. end = s.Length;
  579. if (end == 0)
  580. return s;
  581. int begin = 0;
  582. while (begin < end && (s[begin] < '0' || s[begin] > '9'))
  583. {
  584. begin++;
  585. }
  586. if (begin >= end)
  587. return s;
  588. while (end - begin < digits)
  589. {
  590. s = s.Insert(begin, "0");
  591. end++;
  592. }
  593. return s;
  594. }
  595. // <summary>
  596. // Decode a percent-encoded string. See [method percent_encode].
  597. // </summary>
  598. public static string PercentDecode(this string instance)
  599. {
  600. return Uri.UnescapeDataString(instance);
  601. }
  602. // <summary>
  603. // Percent-encode a string. This is meant to encode parameters in a URL when sending a HTTP GET request and bodies of form-urlencoded POST request.
  604. // </summary>
  605. public static string PercentEncode(this string instance)
  606. {
  607. return Uri.EscapeDataString(instance);
  608. }
  609. // <summary>
  610. // 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].
  611. // </summary>
  612. public static string PlusFile(this string instance, string file)
  613. {
  614. if (instance.Length > 0 && instance[instance.Length - 1] == '/')
  615. return instance + file;
  616. return instance + "/" + file;
  617. }
  618. // <summary>
  619. // Replace occurrences of a substring for different ones inside the string.
  620. // </summary>
  621. public static string Replace(this string instance, string what, string forwhat)
  622. {
  623. return instance.Replace(what, forwhat);
  624. }
  625. // <summary>
  626. // Replace occurrences of a substring for different ones inside the string, but search case-insensitive.
  627. // </summary>
  628. public static string ReplaceN(this string instance, string what, string forwhat)
  629. {
  630. return Regex.Replace(instance, what, forwhat, RegexOptions.IgnoreCase);
  631. }
  632. // <summary>
  633. // Perform a search for a substring, but start from the end of the string instead of the beginning.
  634. // </summary>
  635. public static int RFind(this string instance, string what, int from = -1)
  636. {
  637. return NativeCalls.godot_icall_String_rfind(instance, what, from);
  638. }
  639. // <summary>
  640. // Perform a search for a substring, but start from the end of the string instead of the beginning. Also search case-insensitive.
  641. // </summary>
  642. public static int RFindN(this string instance, string what, int from = -1)
  643. {
  644. return NativeCalls.godot_icall_String_rfindn(instance, what, from);
  645. }
  646. // <summary>
  647. // Return the right side of the string from a given position.
  648. // </summary>
  649. public static string Right(this string instance, int pos)
  650. {
  651. if (pos >= instance.Length)
  652. return instance;
  653. if (pos < 0)
  654. return string.Empty;
  655. return instance.Substring(pos, instance.Length - pos);
  656. }
  657. public static byte[] SHA256Buffer(this string instance)
  658. {
  659. return NativeCalls.godot_icall_String_sha256_buffer(instance);
  660. }
  661. // <summary>
  662. // Return the SHA-256 hash of the string as a string.
  663. // </summary>
  664. public static string SHA256Text(this string instance)
  665. {
  666. return NativeCalls.godot_icall_String_sha256_text(instance);
  667. }
  668. // <summary>
  669. // Return the similarity index of the text compared to this string. 1 means totally similar and 0 means totally dissimilar.
  670. // </summary>
  671. public static float Similarity(this string instance, string text)
  672. {
  673. if (instance == text)
  674. {
  675. // Equal strings are totally similar
  676. return 1.0f;
  677. }
  678. if (instance.Length < 2 || text.Length < 2)
  679. {
  680. // No way to calculate similarity without a single bigram
  681. return 0.0f;
  682. }
  683. string[] sourceBigrams = instance.Bigrams();
  684. string[] targetBigrams = text.Bigrams();
  685. int sourceSize = sourceBigrams.Length;
  686. int targetSize = targetBigrams.Length;
  687. float sum = sourceSize + targetSize;
  688. float inter = 0;
  689. for (int i = 0; i < sourceSize; i++)
  690. {
  691. for (int j = 0; j < targetSize; j++)
  692. {
  693. if (sourceBigrams[i] == targetBigrams[j])
  694. {
  695. inter++;
  696. break;
  697. }
  698. }
  699. }
  700. return 2.0f * inter / sum;
  701. }
  702. // <summary>
  703. // 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 ",".
  704. // </summary>
  705. public static string[] Split(this string instance, string divisor, bool allowEmpty = true)
  706. {
  707. return instance.Split(new[] { divisor }, StringSplitOptions.RemoveEmptyEntries);
  708. }
  709. // <summary>
  710. // 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 ",".
  711. // </summary>
  712. public static float[] SplitFloats(this string instance, string divisor, bool allowEmpty = true)
  713. {
  714. var ret = new List<float>();
  715. int from = 0;
  716. int len = instance.Length;
  717. while (true)
  718. {
  719. int end = instance.Find(divisor, from);
  720. if (end < 0)
  721. end = len;
  722. if (allowEmpty || end > from)
  723. ret.Add(float.Parse(instance.Substring(from)));
  724. if (end == len)
  725. break;
  726. from = end + divisor.Length;
  727. }
  728. return ret.ToArray();
  729. }
  730. private static readonly char[] _nonPrintable = {
  731. (char)00, (char)01, (char)02, (char)03, (char)04, (char)05,
  732. (char)06, (char)07, (char)08, (char)09, (char)10, (char)11,
  733. (char)12, (char)13, (char)14, (char)15, (char)16, (char)17,
  734. (char)18, (char)19, (char)20, (char)21, (char)22, (char)23,
  735. (char)24, (char)25, (char)26, (char)27, (char)28, (char)29,
  736. (char)30, (char)31, (char)32
  737. };
  738. // <summary>
  739. // 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.
  740. // </summary>
  741. public static string StripEdges(this string instance, bool left = true, bool right = true)
  742. {
  743. if (left)
  744. {
  745. if (right)
  746. return instance.Trim(_nonPrintable);
  747. return instance.TrimStart(_nonPrintable);
  748. }
  749. return instance.TrimEnd(_nonPrintable);
  750. }
  751. // <summary>
  752. // Return part of the string from the position [code]from[/code], with length [code]len[/code].
  753. // </summary>
  754. public static string Substr(this string instance, int from, int len)
  755. {
  756. return instance.Substring(from, len);
  757. }
  758. // <summary>
  759. // Convert the String (which is a character array) to PoolByteArray (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.
  760. // </summary>
  761. public static byte[] ToAscii(this string instance)
  762. {
  763. return Encoding.ASCII.GetBytes(instance);
  764. }
  765. // <summary>
  766. // Convert a string, containing a decimal number, into a [code]float[/code].
  767. // </summary>
  768. public static float ToFloat(this string instance)
  769. {
  770. return float.Parse(instance);
  771. }
  772. // <summary>
  773. // Convert a string, containing an integer number, into an [code]int[/code].
  774. // </summary>
  775. public static int ToInt(this string instance)
  776. {
  777. return int.Parse(instance);
  778. }
  779. // <summary>
  780. // Return the string converted to lowercase.
  781. // </summary>
  782. public static string ToLower(this string instance)
  783. {
  784. return instance.ToLower();
  785. }
  786. // <summary>
  787. // Return the string converted to uppercase.
  788. // </summary>
  789. public static string ToUpper(this string instance)
  790. {
  791. return instance.ToUpper();
  792. }
  793. // <summary>
  794. // Convert the String (which is an array of characters) to PoolByteArray (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().
  795. // </summary>
  796. public static byte[] ToUTF8(this string instance)
  797. {
  798. return Encoding.UTF8.GetBytes(instance);
  799. }
  800. // <summary>
  801. // Return a copy of the string with special characters escaped using the XML standard.
  802. // </summary>
  803. public static string XMLEscape(this string instance)
  804. {
  805. return SecurityElement.Escape(instance);
  806. }
  807. // <summary>
  808. // Return a copy of the string with escaped characters replaced by their meanings according to the XML standard.
  809. // </summary>
  810. public static string XMLUnescape(this string instance)
  811. {
  812. return SecurityElement.FromString(instance).Text;
  813. }
  814. }
  815. }