StringExtensions.cs 34 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046
  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, caseSensitive: true)) >= 0)
  19. {
  20. slices++;
  21. pos += splitter.Length;
  22. }
  23. return slices;
  24. }
  25. private static string GetSliceCharacter(this string instance, char splitter, int slice)
  26. {
  27. if (!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, caseSensitive: 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>Find the first occurrence of a substring. Optionally, the search starting position can be passed.</summary>
  278. /// <returns>The starting position of the substring, or -1 if not found.</returns>
  279. public static int Find(this string instance, string what, int from = 0, bool caseSensitive = true)
  280. {
  281. return instance.IndexOf(what, from, caseSensitive ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase);
  282. }
  283. /// <summary>Find the last occurrence of a substring.</summary>
  284. /// <returns>The starting position of the substring, or -1 if not found.</returns>
  285. public static int FindLast(this string instance, string what, bool caseSensitive = true)
  286. {
  287. return instance.FindLast(what, instance.Length - 1, caseSensitive);
  288. }
  289. /// <summary>Find the last occurrence of a substring specifying the search starting position.</summary>
  290. /// <returns>The starting position of the substring, or -1 if not found.</returns>
  291. public static int FindLast(this string instance, string what, int from, bool caseSensitive = true)
  292. {
  293. return instance.LastIndexOf(what, from, caseSensitive ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase);
  294. }
  295. /// <summary>Find the first occurrence of a substring but search as case-insensitive. Optionally, the search starting position can be passed.</summary>
  296. /// <returns>The starting position of the substring, or -1 if not found.</returns>
  297. public static int FindN(this string instance, string what, int from = 0)
  298. {
  299. return instance.IndexOf(what, from, StringComparison.OrdinalIgnoreCase);
  300. }
  301. // <summary>
  302. // If the string is a path to a file, return the base directory.
  303. // </summary>
  304. public static string GetBaseDir(this string instance)
  305. {
  306. int basepos = instance.Find("://");
  307. string rs;
  308. var @base = string.Empty;
  309. if (basepos != -1)
  310. {
  311. var end = basepos + 3;
  312. rs = instance.Substring(end);
  313. @base = instance.Substring(0, end);
  314. }
  315. else
  316. {
  317. if (instance.BeginsWith("/"))
  318. {
  319. rs = instance.Substring(1);
  320. @base = "/";
  321. }
  322. else
  323. {
  324. rs = instance;
  325. }
  326. }
  327. int sep = Mathf.Max(rs.FindLast("/"), rs.FindLast("\\"));
  328. if (sep == -1)
  329. return @base;
  330. return @base + rs.Substr(0, sep);
  331. }
  332. // <summary>
  333. // If the string is a path to a file, return the file and ignore the base directory.
  334. // </summary>
  335. public static string GetFile(this string instance)
  336. {
  337. int sep = Mathf.Max(instance.FindLast("/"), instance.FindLast("\\"));
  338. if (sep == -1)
  339. return instance;
  340. return instance.Substring(sep + 1);
  341. }
  342. // <summary>
  343. // Hash the string and return a 32 bits integer.
  344. // </summary>
  345. public static int Hash(this string instance)
  346. {
  347. int index = 0;
  348. int hashv = 5381;
  349. int c;
  350. while ((c = instance[index++]) != 0)
  351. hashv = (hashv << 5) + hashv + c; // hash * 33 + c
  352. return hashv;
  353. }
  354. // <summary>
  355. // Convert a string containing an hexadecimal number into an int.
  356. // </summary>
  357. public static int HexToInt(this string instance)
  358. {
  359. int sign = 1;
  360. if (instance[0] == '-')
  361. {
  362. sign = -1;
  363. instance = instance.Substring(1);
  364. }
  365. if (!instance.StartsWith("0x"))
  366. return 0;
  367. return sign * int.Parse(instance.Substring(2), NumberStyles.HexNumber);
  368. }
  369. // <summary>
  370. // Insert a substring at a given position.
  371. // </summary>
  372. public static string Insert(this string instance, int pos, string what)
  373. {
  374. return instance.Insert(pos, what);
  375. }
  376. // <summary>
  377. // If the string is a path to a file or directory, return true if the path is absolute.
  378. // </summary>
  379. public static bool IsAbsPath(this string instance)
  380. {
  381. return System.IO.Path.IsPathRooted(instance);
  382. }
  383. // <summary>
  384. // If the string is a path to a file or directory, return true if the path is relative.
  385. // </summary>
  386. public static bool IsRelPath(this string instance)
  387. {
  388. return !System.IO.Path.IsPathRooted(instance);
  389. }
  390. // <summary>
  391. // Check whether this string is a subsequence of the given string.
  392. // </summary>
  393. public static bool IsSubsequenceOf(this string instance, string text, bool caseSensitive = true)
  394. {
  395. int len = instance.Length;
  396. if (len == 0)
  397. return true; // Technically an empty string is subsequence of any string
  398. if (len > text.Length)
  399. return false;
  400. int source = 0;
  401. int target = 0;
  402. while (source < len && target < text.Length)
  403. {
  404. bool match;
  405. if (!caseSensitive)
  406. {
  407. char sourcec = char.ToLower(instance[source]);
  408. char targetc = char.ToLower(text[target]);
  409. match = sourcec == targetc;
  410. }
  411. else
  412. {
  413. match = instance[source] == text[target];
  414. }
  415. if (match)
  416. {
  417. source++;
  418. if (source >= len)
  419. return true;
  420. }
  421. target++;
  422. }
  423. return false;
  424. }
  425. // <summary>
  426. // Check whether this string is a subsequence of the given string, ignoring case differences.
  427. // </summary>
  428. public static bool IsSubsequenceOfI(this string instance, string text)
  429. {
  430. return instance.IsSubsequenceOf(text, caseSensitive: false);
  431. }
  432. // <summary>
  433. // Check whether the string contains a valid float.
  434. // </summary>
  435. public static bool IsValidFloat(this string instance)
  436. {
  437. float f;
  438. return float.TryParse(instance, out f);
  439. }
  440. // <summary>
  441. // Check whether the string contains a valid color in HTML notation.
  442. // </summary>
  443. public static bool IsValidHtmlColor(this string instance)
  444. {
  445. return Color.HtmlIsValid(instance);
  446. }
  447. // <summary>
  448. // 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.
  449. // </summary>
  450. public static bool IsValidIdentifier(this string instance)
  451. {
  452. int len = instance.Length;
  453. if (len == 0)
  454. return false;
  455. for (int i = 0; i < len; i++)
  456. {
  457. if (i == 0)
  458. {
  459. if (instance[0] >= '0' && instance[0] <= '9')
  460. return false; // Don't start with number plz
  461. }
  462. bool validChar = instance[i] >= '0' &&
  463. instance[i] <= '9' || instance[i] >= 'a' &&
  464. instance[i] <= 'z' || instance[i] >= 'A' &&
  465. instance[i] <= 'Z' || instance[i] == '_';
  466. if (!validChar)
  467. return false;
  468. }
  469. return true;
  470. }
  471. // <summary>
  472. // Check whether the string contains a valid integer.
  473. // </summary>
  474. public static bool IsValidInteger(this string instance)
  475. {
  476. int f;
  477. return int.TryParse(instance, out f);
  478. }
  479. // <summary>
  480. // Check whether the string contains a valid IP address.
  481. // </summary>
  482. public static bool IsValidIPAddress(this string instance)
  483. {
  484. // TODO: Support IPv6 addresses
  485. string[] ip = instance.Split(".");
  486. if (ip.Length != 4)
  487. return false;
  488. for (int i = 0; i < ip.Length; i++)
  489. {
  490. string n = ip[i];
  491. if (!n.IsValidInteger())
  492. return false;
  493. int val = n.ToInt();
  494. if (val < 0 || val > 255)
  495. return false;
  496. }
  497. return true;
  498. }
  499. // <summary>
  500. // Return a copy of the string with special characters escaped using the JSON standard.
  501. // </summary>
  502. public static string JSONEscape(this string instance)
  503. {
  504. var sb = new StringBuilder(string.Copy(instance));
  505. sb.Replace("\\", "\\\\");
  506. sb.Replace("\b", "\\b");
  507. sb.Replace("\f", "\\f");
  508. sb.Replace("\n", "\\n");
  509. sb.Replace("\r", "\\r");
  510. sb.Replace("\t", "\\t");
  511. sb.Replace("\v", "\\v");
  512. sb.Replace("\"", "\\\"");
  513. return sb.ToString();
  514. }
  515. // <summary>
  516. // Return an amount of characters from the left of the string.
  517. // </summary>
  518. public static string Left(this string instance, int pos)
  519. {
  520. if (pos <= 0)
  521. return string.Empty;
  522. if (pos >= instance.Length)
  523. return instance;
  524. return instance.Substring(0, pos);
  525. }
  526. /// <summary>
  527. /// Return the length of the string in characters.
  528. /// </summary>
  529. public static int Length(this string instance)
  530. {
  531. return instance.Length;
  532. }
  533. // <summary>
  534. // Do a simple expression match, where '*' matches zero or more arbitrary characters and '?' matches any single character except '.'.
  535. // </summary>
  536. public static bool ExprMatch(this string instance, string expr, bool caseSensitive)
  537. {
  538. if (expr.Length == 0 || instance.Length == 0)
  539. return false;
  540. switch (expr[0])
  541. {
  542. case '\0':
  543. return instance[0] == 0;
  544. case '*':
  545. return ExprMatch(expr + 1, instance, caseSensitive) || instance[0] != 0 && ExprMatch(expr, instance + 1, caseSensitive);
  546. case '?':
  547. return instance[0] != 0 && instance[0] != '.' && ExprMatch(expr + 1, instance + 1, caseSensitive);
  548. default:
  549. return (caseSensitive ? instance[0] == expr[0] : char.ToUpper(instance[0]) == char.ToUpper(expr[0])) &&
  550. ExprMatch(expr + 1, instance + 1, caseSensitive);
  551. }
  552. }
  553. // <summary>
  554. // Do a simple case sensitive expression match, using ? and * wildcards (see [method expr_match]).
  555. // </summary>
  556. public static bool Match(this string instance, string expr, bool caseSensitive = true)
  557. {
  558. return instance.ExprMatch(expr, caseSensitive);
  559. }
  560. // <summary>
  561. // Do a simple case insensitive expression match, using ? and * wildcards (see [method expr_match]).
  562. // </summary>
  563. public static bool MatchN(this string instance, string expr)
  564. {
  565. return instance.ExprMatch(expr, caseSensitive: false);
  566. }
  567. // <summary>
  568. // Return the MD5 hash of the string as an array of bytes.
  569. // </summary>
  570. public static byte[] MD5Buffer(this string instance)
  571. {
  572. return godot_icall_String_md5_buffer(instance);
  573. }
  574. [MethodImpl(MethodImplOptions.InternalCall)]
  575. internal extern static byte[] godot_icall_String_md5_buffer(string str);
  576. // <summary>
  577. // Return the MD5 hash of the string as a string.
  578. // </summary>
  579. public static string MD5Text(this string instance)
  580. {
  581. return godot_icall_String_md5_text(instance);
  582. }
  583. [MethodImpl(MethodImplOptions.InternalCall)]
  584. internal extern static string godot_icall_String_md5_text(string str);
  585. // <summary>
  586. // Perform a case-insensitive comparison to another string, return -1 if less, 0 if equal and +1 if greater.
  587. // </summary>
  588. public static int NocasecmpTo(this string instance, string to)
  589. {
  590. return instance.CompareTo(to, caseSensitive: false);
  591. }
  592. // <summary>
  593. // Return the character code at position [code]at[/code].
  594. // </summary>
  595. public static int OrdAt(this string instance, int at)
  596. {
  597. return instance[at];
  598. }
  599. // <summary>
  600. // Format a number to have an exact number of [code]digits[/code] after the decimal point.
  601. // </summary>
  602. public static string PadDecimals(this string instance, int digits)
  603. {
  604. int c = instance.Find(".");
  605. if (c == -1)
  606. {
  607. if (digits <= 0)
  608. return instance;
  609. instance += ".";
  610. c = instance.Length - 1;
  611. }
  612. else
  613. {
  614. if (digits <= 0)
  615. return instance.Substring(0, c);
  616. }
  617. if (instance.Length - (c + 1) > digits)
  618. {
  619. instance = instance.Substring(0, c + digits + 1);
  620. }
  621. else
  622. {
  623. while (instance.Length - (c + 1) < digits)
  624. {
  625. instance += "0";
  626. }
  627. }
  628. return instance;
  629. }
  630. // <summary>
  631. // Format a number to have an exact number of [code]digits[/code] before the decimal point.
  632. // </summary>
  633. public static string PadZeros(this string instance, int digits)
  634. {
  635. string s = instance;
  636. int end = s.Find(".");
  637. if (end == -1)
  638. end = s.Length;
  639. if (end == 0)
  640. return s;
  641. int begin = 0;
  642. while (begin < end && (s[begin] < '0' || s[begin] > '9'))
  643. {
  644. begin++;
  645. }
  646. if (begin >= end)
  647. return s;
  648. while (end - begin < digits)
  649. {
  650. s = s.Insert(begin, "0");
  651. end++;
  652. }
  653. return s;
  654. }
  655. // <summary>
  656. // Decode a percent-encoded string. See [method percent_encode].
  657. // </summary>
  658. public static string PercentDecode(this string instance)
  659. {
  660. return Uri.UnescapeDataString(instance);
  661. }
  662. // <summary>
  663. // 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.
  664. // </summary>
  665. public static string PercentEncode(this string instance)
  666. {
  667. return Uri.EscapeDataString(instance);
  668. }
  669. // <summary>
  670. // 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].
  671. // </summary>
  672. public static string PlusFile(this string instance, string file)
  673. {
  674. if (instance.Length > 0 && instance[instance.Length - 1] == '/')
  675. return instance + file;
  676. return instance + "/" + file;
  677. }
  678. // <summary>
  679. // Replace occurrences of a substring for different ones inside the string.
  680. // </summary>
  681. public static string Replace(this string instance, string what, string forwhat)
  682. {
  683. return instance.Replace(what, forwhat);
  684. }
  685. // <summary>
  686. // Replace occurrences of a substring for different ones inside the string, but search case-insensitive.
  687. // </summary>
  688. public static string ReplaceN(this string instance, string what, string forwhat)
  689. {
  690. return Regex.Replace(instance, what, forwhat, RegexOptions.IgnoreCase);
  691. }
  692. // <summary>
  693. // Perform a search for a substring, but start from the end of the string instead of the beginning.
  694. // </summary>
  695. public static int RFind(this string instance, string what, int from = -1)
  696. {
  697. return godot_icall_String_rfind(instance, what, from);
  698. }
  699. [MethodImpl(MethodImplOptions.InternalCall)]
  700. internal extern static int godot_icall_String_rfind(string str, string what, int from);
  701. // <summary>
  702. // Perform a search for a substring, but start from the end of the string instead of the beginning. Also search case-insensitive.
  703. // </summary>
  704. public static int RFindN(this string instance, string what, int from = -1)
  705. {
  706. return godot_icall_String_rfindn(instance, what, from);
  707. }
  708. [MethodImpl(MethodImplOptions.InternalCall)]
  709. internal extern static int godot_icall_String_rfindn(string str, string what, int from);
  710. // <summary>
  711. // Return the right side of the string from a given position.
  712. // </summary>
  713. public static string Right(this string instance, int pos)
  714. {
  715. if (pos >= instance.Length)
  716. return instance;
  717. if (pos < 0)
  718. return string.Empty;
  719. return instance.Substring(pos, instance.Length - pos);
  720. }
  721. public static byte[] SHA256Buffer(this string instance)
  722. {
  723. return godot_icall_String_sha256_buffer(instance);
  724. }
  725. [MethodImpl(MethodImplOptions.InternalCall)]
  726. internal extern static byte[] godot_icall_String_sha256_buffer(string str);
  727. // <summary>
  728. // Return the SHA-256 hash of the string as a string.
  729. // </summary>
  730. public static string SHA256Text(this string instance)
  731. {
  732. return godot_icall_String_sha256_text(instance);
  733. }
  734. [MethodImpl(MethodImplOptions.InternalCall)]
  735. internal extern static string godot_icall_String_sha256_text(string str);
  736. // <summary>
  737. // Return the similarity index of the text compared to this string. 1 means totally similar and 0 means totally dissimilar.
  738. // </summary>
  739. public static float Similarity(this string instance, string text)
  740. {
  741. if (instance == text)
  742. {
  743. // Equal strings are totally similar
  744. return 1.0f;
  745. }
  746. if (instance.Length < 2 || text.Length < 2)
  747. {
  748. // No way to calculate similarity without a single bigram
  749. return 0.0f;
  750. }
  751. string[] sourceBigrams = instance.Bigrams();
  752. string[] targetBigrams = text.Bigrams();
  753. int sourceSize = sourceBigrams.Length;
  754. int targetSize = targetBigrams.Length;
  755. float sum = sourceSize + targetSize;
  756. float inter = 0;
  757. for (int i = 0; i < sourceSize; i++)
  758. {
  759. for (int j = 0; j < targetSize; j++)
  760. {
  761. if (sourceBigrams[i] == targetBigrams[j])
  762. {
  763. inter++;
  764. break;
  765. }
  766. }
  767. }
  768. return 2.0f * inter / sum;
  769. }
  770. // <summary>
  771. // 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 ",".
  772. // </summary>
  773. public static string[] Split(this string instance, string divisor, bool allowEmpty = true)
  774. {
  775. return instance.Split(new[] { divisor }, StringSplitOptions.RemoveEmptyEntries);
  776. }
  777. // <summary>
  778. // 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 ",".
  779. // </summary>
  780. public static float[] SplitFloats(this string instance, string divisor, bool allowEmpty = true)
  781. {
  782. var ret = new List<float>();
  783. int from = 0;
  784. int len = instance.Length;
  785. while (true)
  786. {
  787. int end = instance.Find(divisor, from, caseSensitive: true);
  788. if (end < 0)
  789. end = len;
  790. if (allowEmpty || end > from)
  791. ret.Add(float.Parse(instance.Substring(from)));
  792. if (end == len)
  793. break;
  794. from = end + divisor.Length;
  795. }
  796. return ret.ToArray();
  797. }
  798. private static readonly char[] _nonPrintable = {
  799. (char)00, (char)01, (char)02, (char)03, (char)04, (char)05,
  800. (char)06, (char)07, (char)08, (char)09, (char)10, (char)11,
  801. (char)12, (char)13, (char)14, (char)15, (char)16, (char)17,
  802. (char)18, (char)19, (char)20, (char)21, (char)22, (char)23,
  803. (char)24, (char)25, (char)26, (char)27, (char)28, (char)29,
  804. (char)30, (char)31, (char)32
  805. };
  806. // <summary>
  807. // 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.
  808. // </summary>
  809. public static string StripEdges(this string instance, bool left = true, bool right = true)
  810. {
  811. if (left)
  812. {
  813. if (right)
  814. return instance.Trim(_nonPrintable);
  815. return instance.TrimStart(_nonPrintable);
  816. }
  817. return instance.TrimEnd(_nonPrintable);
  818. }
  819. // <summary>
  820. // Return part of the string from the position [code]from[/code], with length [code]len[/code].
  821. // </summary>
  822. public static string Substr(this string instance, int from, int len)
  823. {
  824. int max = instance.Length - from;
  825. return instance.Substring(from, len > max ? max : len);
  826. }
  827. // <summary>
  828. // 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.
  829. // </summary>
  830. public static byte[] ToAscii(this string instance)
  831. {
  832. return Encoding.ASCII.GetBytes(instance);
  833. }
  834. // <summary>
  835. // Convert a string, containing a decimal number, into a [code]float[/code].
  836. // </summary>
  837. public static float ToFloat(this string instance)
  838. {
  839. return float.Parse(instance);
  840. }
  841. // <summary>
  842. // Convert a string, containing an integer number, into an [code]int[/code].
  843. // </summary>
  844. public static int ToInt(this string instance)
  845. {
  846. return int.Parse(instance);
  847. }
  848. // <summary>
  849. // Return the string converted to lowercase.
  850. // </summary>
  851. public static string ToLower(this string instance)
  852. {
  853. return instance.ToLower();
  854. }
  855. // <summary>
  856. // Return the string converted to uppercase.
  857. // </summary>
  858. public static string ToUpper(this string instance)
  859. {
  860. return instance.ToUpper();
  861. }
  862. // <summary>
  863. // 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().
  864. // </summary>
  865. public static byte[] ToUTF8(this string instance)
  866. {
  867. return Encoding.UTF8.GetBytes(instance);
  868. }
  869. // <summary>
  870. // Return a copy of the string with special characters escaped using the XML standard.
  871. // </summary>
  872. public static string XMLEscape(this string instance)
  873. {
  874. return SecurityElement.Escape(instance);
  875. }
  876. // <summary>
  877. // Return a copy of the string with escaped characters replaced by their meanings according to the XML standard.
  878. // </summary>
  879. public static string XMLUnescape(this string instance)
  880. {
  881. return SecurityElement.FromString(instance).Text;
  882. }
  883. }
  884. }