StringExtensions.cs 32 KB

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