StringExtensionMethod.cs 11 KB

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