StringHelper.cs 22 KB

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