StringHelper.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Text;
  5. using System.Text.RegularExpressions;
  6. namespace Assets.Plugins.CommonTool
  7. {
  8. public static class StringHelper
  9. {
  10. #region STRING
  11. /// <summary>
  12. /// 检查空字符串
  13. /// </summary>
  14. /// <param name="str"></param>
  15. /// <returns></returns>
  16. public static bool IsNotEmpty(this string str)
  17. {
  18. return !IsEmpty(str);
  19. }
  20. /// <summary>
  21. /// 检查空字符串
  22. /// </summary>
  23. /// <param name="str"></param>
  24. /// <returns></returns>
  25. public static bool IsEmpty(this string str)
  26. {
  27. return string.IsNullOrEmpty(str);
  28. }
  29. /// <summary>
  30. /// 大写并移除空白字符串
  31. /// </summary>
  32. /// <param name="str"></param>
  33. /// <returns></returns>
  34. public static string UAndT(this string str)
  35. {
  36. if (str == null)
  37. str = "";
  38. return str.ToUpper().Trim();
  39. }
  40. /// <summary>
  41. /// 大写并移除空白字符串
  42. /// </summary>
  43. /// <param name="obj"></param>
  44. /// <returns></returns>
  45. public static string UAndT(this object obj)
  46. {
  47. return UAndT(obj.ToString());
  48. }
  49. /// <summary>
  50. /// 检查是否以某字符串开头,不是加上此字符串
  51. /// </summary>
  52. /// <param name="str"></param>
  53. /// <param name="startStr"></param>
  54. /// <returns></returns>
  55. public static string Sw(this string str, string startStr)
  56. {
  57. return str.StartsWith(startStr) ? str : $"{startStr}{str}";
  58. }
  59. /// <summary>
  60. /// 检查是否以某字符串结尾,不是加上此字符串
  61. /// </summary>
  62. /// <param name="str"></param>
  63. /// <param name="endStr"></param>
  64. /// <returns></returns>
  65. public static string Ew(this string str, string endStr)
  66. {
  67. return str.EndsWith(endStr) ? str : $"{str}{endStr}";
  68. }
  69. /// <summary>
  70. /// 前补全
  71. /// </summary>
  72. /// <param name="i"></param>
  73. /// <param name="num"></param>
  74. /// <param name="charStr"></param>
  75. /// <returns></returns>
  76. public static string LeftPad(this int i, int num, string charStr = "0")
  77. {
  78. return i.ToString().PadLeft(num, Convert.ToChar(charStr));
  79. }
  80. /// <summary>
  81. /// 后补全
  82. /// </summary>
  83. /// <param name="i"></param>
  84. /// <param name="num"></param>
  85. /// <param name="charStr"></param>
  86. /// <returns></returns>
  87. public static string RightPad(this int i, int num, string charStr = "0")
  88. {
  89. return i.ToString().PadRight(num, Convert.ToChar(charStr));
  90. }
  91. /// <summary>
  92. /// 前补全
  93. /// </summary>
  94. /// <param name="s"></param>
  95. /// <param name="num"></param>
  96. /// <param name="charStr"></param>
  97. /// <returns></returns>
  98. public static string LeftPad(this string s, int num, string charStr = "0")
  99. {
  100. return s.PadLeft(num, Convert.ToChar(charStr));
  101. }
  102. /// <summary>
  103. /// 后补全
  104. /// </summary>
  105. /// <param name="s"></param>
  106. /// <param name="num"></param>
  107. /// <param name="charStr"></param>
  108. /// <returns></returns>
  109. public static string RightPad(this string s, int num, string charStr = "0")
  110. {
  111. return s.PadRight(num, Convert.ToChar(charStr));
  112. }
  113. /// <summary>
  114. /// 复制
  115. /// </summary>
  116. /// <param name="str"></param>
  117. /// <param name="count">复制次数</param>
  118. /// <returns></returns>
  119. public static string Replicate(this string str, int count)
  120. {
  121. string str2 = "";
  122. for (int index = 0; index < count; ++index)
  123. str2 += str;
  124. return str2;
  125. }
  126. /// <summary>
  127. /// 末尾移除匹配
  128. /// </summary>
  129. /// <param name="source"></param>
  130. /// <param name="removeStr"></param>
  131. /// <returns></returns>
  132. public static string TrimEnd(string source, string removeStr)
  133. {
  134. char[] charArray = removeStr.ToCharArray();
  135. return source.TrimEnd(charArray);
  136. }
  137. /// <summary>
  138. /// 截取字符串中开始和结束字符串中间的字符串
  139. /// </summary>
  140. /// <param name="source">源字符串</param>
  141. /// <param name="startStr">开始字符串</param>
  142. /// <param name="endStr">结束字符串</param>
  143. /// <returns>中间字符串</returns>
  144. public static string SubstringSingle(this string source, string startStr, string endStr)
  145. {
  146. Regex rg = new Regex("(?<=(" + startStr + "))[.\\s\\S]*?(?=(" + endStr + "))", RegexOptions.Multiline | RegexOptions.Singleline);
  147. return rg.Match(source).Value;
  148. }
  149. /// <summary>
  150. /// (批量)截取字符串中开始和结束字符串中间的字符串
  151. /// </summary>
  152. /// <param name="source">源字符串</param>
  153. /// <param name="startStr">开始字符串</param>
  154. /// <param name="endStr">结束字符串</param>
  155. /// <returns>中间字符串</returns>
  156. public static List<string> SubstringMultiple(this string source, string startStr, string endStr)
  157. {
  158. Regex rg = new Regex("(?<=(" + startStr + "))[.\\s\\S]*?(?=(" + endStr + "))", RegexOptions.Multiline | RegexOptions.Singleline);
  159. MatchCollection matches = rg.Matches(source);
  160. List<string> resList = new List<string>();
  161. foreach (Match item in matches)
  162. resList.Add(item.Value);
  163. return resList;
  164. }
  165. private static Random _random;
  166. public static string GetRandom()
  167. {
  168. if (_random == null)
  169. {
  170. _random = new Random(0x989680);
  171. }
  172. return "R" + _random.Next(0x989680, 0x5f5e0ff);
  173. }
  174. public static int GetRandomSeed()
  175. {
  176. byte[] bytes = new byte[4];
  177. var rng = new System.Security.Cryptography.RNGCryptoServiceProvider();
  178. rng.GetBytes(bytes);
  179. return BitConverter.ToInt32(bytes, 0);
  180. }
  181. public static string FormatXml2Code(this string str)
  182. {
  183. return str.Replace(";amp;", "&").Replace(";lt;", "<").Replace(";gt;", ">");
  184. }
  185. public static string FormatCode2Xml(this string str)
  186. {
  187. return str.Replace("&", ";amp;").Replace("<", ";lt;").Replace(">", ";gt;");
  188. }
  189. public static string AddStr(this string source, object toBeAppended)
  190. {
  191. source = source.Trim();
  192. if (source == "")
  193. {
  194. return GetDelimitedStr(toBeAppended);
  195. }
  196. if ((source[0] == '[') && (source[source.Length - 1] == ']'))
  197. {
  198. return (source + $",[{toBeAppended.ToString().Trim()}]");
  199. }
  200. return JoinString(source, toBeAppended);
  201. }
  202. public static string JoinString(this object first, object second)
  203. {
  204. return $"[{first.ToString().Trim()}],[{second.ToString().Trim()}]";
  205. }
  206. public static string JoinString(this object first, object[] second)
  207. {
  208. var str = "";
  209. foreach (var o in second)
  210. {
  211. str += $",[{o.ToString().Trim()}]";
  212. }
  213. return $"[{first.ToString().Trim()}]{str}";
  214. }
  215. public static string JoinString(this object[] second)
  216. {
  217. var str = "";
  218. foreach (var o in second)
  219. {
  220. str += (str == "" ? "" : ",") + $"[{o.ToString().Trim()}]";
  221. }
  222. return str;
  223. }
  224. public static string JoinString(this object first, object second, object poThird)
  225. {
  226. return $"[{first.ToString().Trim()}],[{second.ToString().Trim()}], [{poThird.ToString().Trim()}]";
  227. }
  228. public static string JoinString(this object first, object second, object poThird, object poFourth)
  229. {
  230. return
  231. $"[{first.ToString().Trim()}],[{second.ToString().Trim()}], [{poThird.ToString().Trim()}], [{poFourth.ToString().Trim()}]";
  232. }
  233. public static string AppendToStr(this string source, object toBeAppended)
  234. {
  235. string delimitedStr = GetDelimitedStr(toBeAppended);
  236. source = source.Trim();
  237. if (source != "")
  238. {
  239. delimitedStr = source + "," + delimitedStr;
  240. }
  241. return delimitedStr;
  242. }
  243. #endregion STRING
  244. #region INT,DECIMAL,BOOL
  245. /// <summary>
  246. /// 验证int,并返回
  247. /// </summary>
  248. /// <param name="str"></param>
  249. /// <returns></returns>
  250. public static int ValI(this string str)
  251. {
  252. return (int)ValD(str);
  253. }
  254. /// <summary>
  255. /// 验证decimal,并返回
  256. /// </summary>
  257. /// <param name="str"></param>
  258. /// <returns></returns>
  259. public static decimal ValD(this string str)
  260. {
  261. string str1 = "";
  262. foreach (var ch in str)
  263. {
  264. if (ch != ' ' && ch != ',')
  265. {
  266. if (ch >= '0' && ch <= '9')
  267. str1 += ch.ToString();
  268. else if ((ch == '+' || ch == '-') && str1 == "")
  269. str1 += ch.ToString();
  270. else if (ch == '.' && str1.IndexOf(ch) < 0)
  271. str1 += ch.ToString();
  272. else
  273. break;
  274. }
  275. }
  276. if (str1 == "")
  277. str1 = "0";
  278. else if (str1 == "-")
  279. str1 = "-0";
  280. return Convert.ToDecimal(str1);
  281. }
  282. /// <summary>
  283. /// int转bool (true,yes,y,>1)
  284. /// </summary>
  285. /// <param name="i"></param>
  286. /// <returns></returns>
  287. public static bool ValB(this int i)
  288. {
  289. var str = i > 0 ? "1" : "0";
  290. return StrToBool(str);
  291. }
  292. /// <summary>
  293. /// 字符串转bool (true,yes,y,1)
  294. /// </summary>
  295. /// <param name="str"></param>
  296. /// <returns></returns>
  297. public static bool ValB(this string str)
  298. {
  299. return StrToBool(str);
  300. }
  301. /// <summary>
  302. /// 字符串转bool (true,yes,y,1)
  303. /// </summary>
  304. /// <param name="str"></param>
  305. /// <returns></returns>
  306. public static bool StrToBool(this string str)
  307. {
  308. bool flag = false;
  309. str = UAndT(str);
  310. if (str == "TRUE" || str == "YES" || str == "Y" || str == "1")
  311. flag = true;
  312. return flag;
  313. }
  314. #endregion INT,DECIMAL,BOOL
  315. #region Array
  316. /// <summary>
  317. /// 字符转数组
  318. /// </summary>
  319. /// <param name="str"></param>
  320. /// <param name="separator">分隔符默认:,</param>
  321. /// <returns></returns>
  322. public static string[] StrToArray(this string str, string separator = ",")
  323. {
  324. return (string[])StrToArrayEx(str, separator);
  325. }
  326. /// <summary>
  327. /// 字符转数组
  328. /// </summary>
  329. /// <param name="str"></param>
  330. /// <param name="separator">分隔符默认:,</param>
  331. /// <returns></returns>
  332. public static Array StrToArrayEx(this string str, string separator = ",")
  333. {
  334. ArrayList arrayList = new ArrayList();
  335. str = str == null ? "" : str.Trim();
  336. int length1 = separator.Length;
  337. int length2;
  338. for (; str.Length > 0; str = length2 + length1 <= str.Length ? str.Substring(length2 + length1).Trim() : "")
  339. {
  340. length2 = str.IndexOf(separator, StringComparison.Ordinal);
  341. int num1 = str.IndexOf("[", StringComparison.Ordinal);
  342. if (num1 >= 0 && num1 < length2)
  343. {
  344. int num2 = 1;
  345. int length3 = str.Length;
  346. int startIndex;
  347. for (startIndex = num1 + 1; startIndex < length3; ++startIndex)
  348. {
  349. switch (str[startIndex])
  350. {
  351. case '[':
  352. ++num2;
  353. break;
  354. case ']':
  355. --num2;
  356. break;
  357. }
  358. if (num2 == 0)
  359. break;
  360. }
  361. length2 = str.IndexOf(separator, startIndex, StringComparison.Ordinal);
  362. }
  363. if (length2 < 0)
  364. length2 = str.Length;
  365. string str1 = str.Substring(0, length2);
  366. int length4 = str1.Length;
  367. if (length4 > 0 && str1[0] == '[' && str1[length4 - 1] == ']')
  368. str1 = str1.Substring(1, length4 - 2);
  369. arrayList.Add(str1.Trim());
  370. }
  371. Array instance = new string[arrayList.Count];
  372. arrayList.CopyTo(instance);
  373. return instance;
  374. }
  375. /// <summary>
  376. /// 数组转字符串 (分隔符:,)
  377. /// </summary>
  378. /// <param name="paStr"></param>
  379. /// <param name="delimited"></param>
  380. /// <returns></returns>
  381. public static string ArrayToStr(this Array paStr, bool delimited = false)
  382. {
  383. return ArrayToStr(paStr, ",", delimited);
  384. }
  385. /// <summary>
  386. /// 数组转字符串
  387. /// </summary>
  388. /// <param name="paStr"></param>
  389. /// <param name="separator"></param>
  390. /// <param name="delimited">是否加界定符“[]”</param>
  391. /// <returns></returns>
  392. public static string ArrayToStr(this Array paStr, string separator, bool delimited = false)
  393. {
  394. string str1 = "";
  395. foreach (string str2 in paStr)
  396. str1 = str1 + (str1 == "" ? "" : separator) + (delimited ? GetDelimitedStr(str2) : str2);
  397. return str1;
  398. }
  399. /// <summary>
  400. /// 加上界定符
  401. /// </summary>
  402. /// <param name="obj"></param>
  403. /// <returns></returns>
  404. public static string GetDelimitedStr(object obj)
  405. {
  406. return "[" + obj + "]";
  407. }
  408. /// <summary>
  409. /// 改编
  410. /// </summary>
  411. /// <param name="arr"></param>
  412. /// <param name="from"></param>
  413. /// <param name="to"></param>
  414. /// <returns></returns>
  415. public static Array RearrangeArray(this Array arr, int from, int to)
  416. {
  417. Array instance = new object[arr.Length];
  418. arr.CopyTo(instance, 0);
  419. object obj = instance.GetValue(from);
  420. if (from > to)
  421. {
  422. for (int index = from - 1; index >= to; --index)
  423. instance.SetValue(instance.GetValue(index), index + 1);
  424. }
  425. else
  426. {
  427. for (int index = from + 1; index <= to; ++index)
  428. instance.SetValue(instance.GetValue(index), index - 1);
  429. }
  430. instance.SetValue(obj, to);
  431. return instance;
  432. }
  433. /// <summary>
  434. /// 数组转数组List
  435. /// </summary>
  436. /// <param name="arr"></param>
  437. /// <returns></returns>
  438. public static ArrayList ArrayToArrayList(this Array arr)
  439. {
  440. ArrayList arrayList = new ArrayList();
  441. foreach (object obj in arr)
  442. arrayList.Add(obj);
  443. return arrayList;
  444. }
  445. /// <summary>
  446. /// 移除
  447. /// </summary>
  448. /// <param name="arr"></param>
  449. /// <param name="obj"></param>
  450. /// <returns></returns>
  451. public static Array RemoveFromArray(this Array arr, object obj)
  452. {
  453. ArrayList arrayList = ArrayToArrayList(arr);
  454. arrayList.Remove(obj);
  455. Array instance = new object[arrayList.Count];
  456. arrayList.CopyTo(instance);
  457. return instance;
  458. }
  459. /// <summary>
  460. /// 数组list 插入(按字符串长度排序)
  461. /// </summary>
  462. /// <param name="poArrayList"></param>
  463. /// <param name="pcName"></param>
  464. public static void InsertIdentifier(this ArrayList poArrayList, string pcName)
  465. {
  466. int index = 0;
  467. while (index < poArrayList.Count)
  468. {
  469. string str = poArrayList[index].ToString();
  470. if (str == pcName)
  471. {
  472. index = -1;
  473. break;
  474. }
  475. if (str.Length < pcName.Length)
  476. {
  477. break;
  478. }
  479. index++;
  480. }
  481. if (index >= 0)
  482. {
  483. poArrayList.Insert(index, pcName);
  484. }
  485. }
  486. #endregion Array
  487. #region DateTime
  488. /// <summary>
  489. /// 时间转字符串
  490. /// </summary>
  491. /// <param name="dateTime"></param>
  492. /// <returns></returns>
  493. public static string DtToStr(this DateTime dateTime)
  494. {
  495. return dateTime.ToString("s").Replace("T", " ");
  496. }
  497. /// <summary>
  498. /// 字符串转时间
  499. /// </summary>
  500. /// <param name="str"></param>
  501. /// <returns></returns>
  502. public static DateTime StrToDt(this string str)
  503. {
  504. DateTime dateTime = new DateTime(1900, 1, 1);
  505. try
  506. {
  507. dateTime = DateTime.Parse(str);
  508. }
  509. catch (Exception)
  510. {
  511. // ignored
  512. }
  513. return dateTime;
  514. }
  515. /// <summary>
  516. /// 日期转指定格式日期(默认yyyyMMddHHmmss)
  517. /// </summary>
  518. /// <param name="dateTime"></param>
  519. /// <param name="formatter"></param>
  520. /// <returns></returns>
  521. public static string DtToStrFormatter(this DateTime dateTime, string formatter = "yyyyMMddHHmmss")
  522. {
  523. return dateTime.ToString(formatter);
  524. }
  525. /// <summary>
  526. /// 日期转时间字符串
  527. /// </summary>
  528. /// <param name="dateTime"></param>
  529. /// <returns></returns>
  530. public static string DtToTimeStr(this DateTime dateTime)
  531. {
  532. return dateTime.ToString("T");
  533. }
  534. /// <summary>
  535. /// 日期转日期字符串
  536. /// </summary>
  537. /// <param name="dateTime"></param>
  538. /// <returns></returns>
  539. public static string DtToDateStr(this DateTime dateTime)
  540. {
  541. return dateTime.ToString("d");
  542. }
  543. /// <summary>
  544. /// 获取秒
  545. /// </summary>
  546. /// <param name="dateTime"></param>
  547. /// <returns></returns>
  548. public static int DtToSeconds(this DateTime dateTime)
  549. {
  550. return dateTime.TimeOfDay.Seconds;
  551. }
  552. /// <summary>
  553. /// 今天之后多少秒
  554. /// </summary>
  555. /// <param name="seconds"></param>
  556. /// <returns></returns>
  557. public static DateTime DtFromSeconds(int seconds)
  558. {
  559. return DateTime.Today + new TimeSpan(0, 0, seconds);
  560. }
  561. /// <summary>
  562. /// 时间差(分)
  563. /// </summary>
  564. /// <param name="start"></param>
  565. /// <param name="end"></param>
  566. /// <returns></returns>
  567. public static int GetTimeSpanMinute(this DateTime start, DateTime end)
  568. {
  569. return Convert.ToInt32(GetTimeSpan(start, end).TotalMinutes);
  570. }
  571. /// <summary>
  572. /// 时间差
  573. /// </summary>
  574. /// <param name="start"></param>
  575. /// <param name="end"></param>
  576. /// <returns></returns>
  577. public static TimeSpan GetTimeSpan(this DateTime start, DateTime end)
  578. {
  579. TimeSpan timeSpan = end - start;
  580. return timeSpan;
  581. }
  582. #endregion DateTime
  583. #region BASE64
  584. /// <summary>
  585. /// Base64 编码
  586. /// </summary>
  587. /// <param name="encode">编码方式</param>
  588. /// <param name="source">要编码的字符串</param>
  589. /// <returns>返回编码后的字符串</returns>
  590. public static string EncodeBase64(this string source, Encoding encode = null)
  591. {
  592. string result;
  593. try
  594. {
  595. encode ??= Encoding.UTF8;
  596. byte[] bytes = encode.GetBytes(source);
  597. result = Convert.ToBase64String(bytes);
  598. }
  599. catch
  600. {
  601. result = source;
  602. }
  603. return result;
  604. }
  605. /// <summary>
  606. /// Base64 解码
  607. /// </summary>
  608. /// <param name="encode">解码方式</param>
  609. /// <param name="source">要解码的字符串</param>
  610. /// <returns>返回解码后的字符串</returns>
  611. public static string DecodeBase64(this string source, Encoding encode = null)
  612. {
  613. string result;
  614. try
  615. {
  616. byte[] bytes = Convert.FromBase64String(source);
  617. encode ??= Encoding.UTF8;
  618. result = encode.GetString(bytes);
  619. }
  620. catch
  621. {
  622. result = source;
  623. }
  624. return result;
  625. }
  626. #endregion
  627. }
  628. }