StringExtensions.cs 34 KB

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