StringExtensionMethod.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Globalization;
  4. using System.Linq;
  5. using System.Security.Cryptography;
  6. using System.Text;
  7. using System.Text.RegularExpressions;
  8. using System.Threading;
  9. using System.Threading.Tasks;
  10. namespace ProjectBase.Util
  11. {
  12. /// <summary>
  13. /// 用于字符串转换其他类型的扩展函数
  14. /// </summary>
  15. public static class StringExtensionMethod
  16. {
  17. #region 字符串转换其他格式
  18. /// <summary>
  19. /// 转换字符串为日期类型
  20. /// </summary>
  21. /// <param name="str">字符串内容</param>
  22. /// <param name="defaultValue">默认值</param>
  23. /// <returns></returns>
  24. public static DateTime ToDateTime(this string str)
  25. {
  26. str = ConvertHelper.ConvertToDBC(str);//先转换为半角字符串
  27. DateTime defaultValue = Convert.ToDateTime("1900-1-1");
  28. bool converted = DateTime.TryParse(str, out defaultValue);
  29. return defaultValue;
  30. }
  31. /// <summary>
  32. /// 转换字符串为Int类型,可以指定默认值
  33. /// </summary>
  34. /// <param name="str">字符串内容</param>
  35. /// <param name="defaultValue">默认值</param>
  36. /// <returns></returns>
  37. public static int ToInt32(this string str, int defaultValue = 0)
  38. {
  39. str = ConvertHelper.ConvertToDBC(str);//先转换为半角字符串
  40. bool converted = int.TryParse(str, out defaultValue);
  41. return defaultValue;
  42. }
  43. /// <summary>
  44. /// 转换字符串为Int16类型,可以指定默认值
  45. /// </summary>
  46. /// <param name="str">字符串内容</param>
  47. /// <param name="defaultValue">默认值</param>
  48. /// <returns></returns>
  49. public static int ToInt16(this string str, Int16 defaultValue = 0)
  50. {
  51. str = ConvertHelper.ConvertToDBC(str);//先转换为半角字符串
  52. bool converted = Int16.TryParse(str, out defaultValue);
  53. return defaultValue;
  54. }
  55. /// <summary>
  56. /// 转换字符串为byte类型,可以指定默认值
  57. /// </summary>
  58. /// <param name="str">字符串内容</param>
  59. /// <param name="defaultValue">默认值</param>
  60. /// <returns></returns>
  61. public static byte ToByte(this string str, byte defaultValue = 0)
  62. {
  63. str = ConvertHelper.ConvertToDBC(str);//先转换为半角字符串
  64. bool converted = byte.TryParse(str, out defaultValue);
  65. return defaultValue;
  66. }
  67. /// <summary>
  68. /// 转换字符串为double类型,可以指定默认值
  69. /// </summary>
  70. /// <param name="str">字符串内容</param>
  71. /// <param name="defaultValue">默认值</param>
  72. /// <returns></returns>
  73. public static double ToDouble(this string str, double defaultValue = 0)
  74. {
  75. str = ConvertHelper.ConvertToDBC(str);//先转换为半角字符串
  76. bool converted = double.TryParse(str, out defaultValue);
  77. return defaultValue;
  78. }
  79. /// <summary>
  80. /// 转换字符串为decimal类型,可以指定默认值
  81. /// </summary>
  82. /// <param name="str">字符串内容</param>
  83. /// <param name="defaultValue">默认值</param>
  84. /// <returns></returns>
  85. public static decimal ToDecimal(this string str, decimal defaultValue = 0M)
  86. {
  87. str = ConvertHelper.ConvertToDBC(str);//先转换为半角字符串
  88. bool converted = decimal.TryParse(str, out defaultValue);
  89. return defaultValue;
  90. }
  91. /// <summary>
  92. /// 转换字符串为float类型,可以指定默认值
  93. /// </summary>
  94. /// <param name="str">字符串内容</param>
  95. /// <param name="defaultValue">默认值</param>
  96. /// <returns></returns>
  97. public static float ToFloat(this string str, float defaultValue = 0)
  98. {
  99. str = ConvertHelper.ConvertToDBC(str);//先转换为半角字符串
  100. bool converted = float.TryParse(str, out defaultValue);
  101. return defaultValue;
  102. }
  103. /// <summary>
  104. /// 转换字符串为float类型,可以指定默认值
  105. /// </summary>
  106. /// <param name="str">字符串内容</param>
  107. /// <returns></returns>
  108. public static bool ToBoolean(this string str)
  109. {
  110. bool defaultValue = false;
  111. bool converted = bool.TryParse(str, out defaultValue);
  112. return defaultValue;
  113. }
  114. /// <summary>
  115. /// 字符串转换为指定格式的列表
  116. /// </summary>
  117. /// <typeparam name="T"></typeparam>
  118. /// <param name="value">字符串内容</param>
  119. /// <param name="delimiter">分隔符号</param>
  120. /// <returns></returns>
  121. public static List<T> ToDelimitedList<T>(this string value, string delimiter)
  122. {
  123. if (value == null)
  124. {
  125. return new List<T>();
  126. }
  127. var output = value.Split(new string[] { delimiter }, StringSplitOptions.RemoveEmptyEntries);
  128. return output.Select(x => (T)Convert.ChangeType(x, typeof(T))).ToList();
  129. }
  130. /// <summary>
  131. /// 字符串转换为指定格式的列表
  132. /// </summary>
  133. /// <typeparam name="T"></typeparam>
  134. /// <param name="value">字符串内容</param>
  135. /// <param name="delimiter">分隔符号</param>
  136. /// <param name="converter">提供的转换操作</param>
  137. /// <returns></returns>
  138. public static List<T> ToDelimitedList<T>(this string value, string delimiter, Func<string, T> converter)
  139. {
  140. if (value == null)
  141. {
  142. return new List<T>();
  143. }
  144. var output = value.Split(new string[] { delimiter }, StringSplitOptions.RemoveEmptyEntries);
  145. return output.Select(converter).ToList();
  146. }
  147. /// <summary>
  148. /// 根据长度分割不同的字符串到列表里面
  149. /// </summary>
  150. /// <param name="value">字符串内容</param>
  151. /// <param name="length">分割的长度</param>
  152. /// <returns></returns>
  153. public static IEnumerable<string> SplitEvery(this string value, int length)
  154. {
  155. int index = 0;
  156. while (index + length < value.Length)
  157. {
  158. yield return value.Substring(index, length);
  159. index += length;
  160. }
  161. if (index < value.Length)
  162. yield return value.Substring(index, value.Length - index);
  163. }
  164. #endregion
  165. #region 其他辅助方法
  166. /// <summary>
  167. /// true, if is valid email address
  168. /// </summary>
  169. /// <param name="s">email address to test</param>
  170. /// <returns>true, if is valid email address</returns>
  171. public static bool IsValidEmailAddress(this string s)
  172. {
  173. return new Regex(@"^[\w-\.]+@([\w-]+\.)+[\w-]{2,6}$").IsMatch(s);
  174. }
  175. /// <summary>
  176. /// Checks if url is valid.
  177. /// </summary>
  178. /// <param name="url"></param>
  179. /// <returns></returns>
  180. public static bool IsValidUrl(this string url)
  181. {
  182. string strRegex = "^(https?://)"
  183. + "?(([0-9a-z_!~*'().&=+$%-]+: )?[0-9a-z_!~*'().&=+$%-]+@)?" //user@
  184. + @"(([0-9]{1,3}\.){3}[0-9]{1,3}" // IP- 199.194.52.184
  185. + "|" // allows either IP or domain
  186. + @"([0-9a-z_!~*'()-]+\.)*" // tertiary domain(s)- www.
  187. + @"([0-9a-z][0-9a-z-]{0,61})?[0-9a-z]" // second level domain
  188. + @"(\.[a-z]{2,6})?)" // first level domain- .com or .museum is optional
  189. + "(:[0-9]{1,5})?" // port number- :80
  190. + "((/?)|" // a slash isn't required if there is no file name
  191. + "(/[0-9a-z_!~*'().;?:@&=+$,%#-]+)+/?)$";
  192. return new Regex(strRegex).IsMatch(url);
  193. }
  194. /// <summary>
  195. /// Check if url (http) is available.
  196. /// </summary>
  197. /// <param name="httpUri">url to check</param>
  198. /// <example>
  199. /// string url = "www.codeproject.com;
  200. /// if( !url.UrlAvailable())
  201. /// ...codeproject is not available
  202. /// </example>
  203. /// <returns>true if available</returns>
  204. //public static bool UrlAvailable(this string httpUrl)
  205. //{
  206. // if (!httpUrl.StartsWith("http://") || !httpUrl.StartsWith("https://"))
  207. // httpUrl = "http://" + httpUrl;
  208. // try
  209. // {
  210. // HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(httpUrl);
  211. // myRequest.Method = "GET";
  212. // myRequest.ContentType = "application/x-www-form-urlencoded";
  213. // HttpWebResponse myHttpWebResponse = (HttpWebResponse)myRequest.GetResponse();
  214. // return true;
  215. // }
  216. // catch
  217. // {
  218. // return false;
  219. // }
  220. //}
  221. /// <summary>
  222. /// Reverse the string
  223. /// </summary>
  224. /// <param name="input"></param>
  225. /// <returns></returns>
  226. public static string Reverse(this string input)
  227. {
  228. char[] chars = input.ToCharArray();
  229. Array.Reverse(chars);
  230. return new String(chars);
  231. }
  232. /// <summary>
  233. /// Reduce string to shorter preview which is optionally ended by some string (...).
  234. /// </summary>
  235. /// <param name="s">string to reduce</param>
  236. /// <param name="count">Length of returned string including endings.</param>
  237. /// <param name="endings">optional edings of reduced text</param>
  238. /// <example>
  239. /// string description = "This is very long description of something";
  240. /// string preview = description.Reduce(20,"...");
  241. /// produce -> "This is very long..."
  242. /// </example>
  243. /// <returns></returns>
  244. public static string Reduce(this string s, int count, string endings)
  245. {
  246. if (count < endings.Length)
  247. throw new Exception("Failed to reduce to less then endings length.");
  248. int sLength = s.Length;
  249. int len = sLength;
  250. if (endings != null)
  251. len += endings.Length;
  252. if (count > sLength)
  253. return s; //it's too short to reduce
  254. s = s.Substring(0, sLength - len + count);
  255. if (endings != null)
  256. s += endings;
  257. return s;
  258. }
  259. /// <summary>
  260. /// remove white space, not line end
  261. /// Useful when parsing user input such phone,
  262. /// price int.Parse("1 000 000".RemoveSpaces(),.....
  263. /// </summary>
  264. /// <param name="s"></param>
  265. /// <param name="value">string without spaces</param>
  266. public static string RemoveSpaces(this string s)
  267. {
  268. return s.Replace(" ", "");
  269. }
  270. /// <summary>
  271. /// true, if the string can be parse as Double respective Int32
  272. /// Spaces are not considred.
  273. /// </summary>
  274. /// <param name="s">input string</param>
  275. /// <param name="floatpoint">true, if Double is considered,
  276. /// otherwhise Int32 is considered.</param>
  277. /// <returns>true, if the string contains only digits or float-point</returns>
  278. public static bool IsNumber(this string s, bool floatpoint)
  279. {
  280. int i;
  281. double d;
  282. string withoutWhiteSpace = s.RemoveSpaces();
  283. if (floatpoint)
  284. {
  285. return double.TryParse(withoutWhiteSpace, NumberStyles.Any,
  286. Thread.CurrentThread.CurrentUICulture, out d);
  287. }
  288. else
  289. {
  290. return int.TryParse(withoutWhiteSpace, out i);
  291. }
  292. }
  293. /// <summary>
  294. /// true, if the string contains only digits or float-point.
  295. /// Spaces are not considred.
  296. /// </summary>
  297. /// <param name="s">input string</param>
  298. /// <param name="floatpoint">true, if float-point is considered</param>
  299. /// <returns>true, if the string contains only digits or float-point</returns>
  300. public static bool IsNumberOnly(this string s, bool floatpoint)
  301. {
  302. s = s.Trim();
  303. if (s.Length == 0)
  304. return false;
  305. foreach (char c in s)
  306. {
  307. if (!char.IsDigit(c))
  308. {
  309. if (floatpoint && (c == '.' || c == ','))
  310. continue;
  311. return false;
  312. }
  313. }
  314. return true;
  315. }
  316. /// <summary>
  317. /// Remove accent from strings
  318. /// </summary>
  319. /// <example>
  320. /// input: "Příliš žluťoučký kůň úpěl ďábelské ódy."
  321. /// result: "Prilis zlutoucky kun upel dabelske ody."
  322. /// </example>
  323. /// <param name="s"></param>
  324. /// <remarks>founded at http://stackoverflow.com/questions/249087/
  325. /// how-do-i-remove-diacritics-accents-from-a-string-in-net</remarks>
  326. /// <returns>string without accents</returns>
  327. public static string RemoveDiacritics(this string s)
  328. {
  329. string stFormD = s.Normalize(NormalizationForm.FormD);
  330. StringBuilder sb = new StringBuilder();
  331. for (int ich = 0; ich < stFormD.Length; ich++)
  332. {
  333. UnicodeCategory uc = CharUnicodeInfo.GetUnicodeCategory(stFormD[ich]);
  334. if (uc != UnicodeCategory.NonSpacingMark)
  335. {
  336. sb.Append(stFormD[ich]);
  337. }
  338. }
  339. return (sb.ToString().Normalize(NormalizationForm.FormC));
  340. }
  341. /// <summary>
  342. /// Replace \r\n or \n by <br />
  343. /// </summary>
  344. /// <param name="s"></param>
  345. /// <returns></returns>
  346. public static string Nl2Br(this string s)
  347. {
  348. return s.Replace("\r\n", "<br />").Replace("\n", "<br />");
  349. }
  350. static MD5CryptoServiceProvider s_md5 = null;
  351. /// <summary>
  352. /// 使用MD5加密字符串
  353. /// </summary>
  354. /// <param name="s">输入字符串</param>
  355. /// <returns></returns>
  356. public static string MD5(this string s)
  357. {
  358. if (s_md5 == null) //creating only when needed
  359. s_md5 = new MD5CryptoServiceProvider();
  360. Byte[] newdata = Encoding.Default.GetBytes(s);
  361. Byte[] encrypted = s_md5.ComputeHash(newdata);
  362. return BitConverter.ToString(encrypted).Replace("-", "").ToLower();
  363. }
  364. #endregion
  365. }
  366. }