using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
namespace ProjectBase.Controls.Others
{
///
/// 用于字符串转换其他类型的扩展函数
///
internal static class StringExtensionMethod
{
#region 字符串转换其他格式
///
/// 转换字符串为float类型,可以指定默认值
///
/// 字符串内容
///
public static bool ToBoolean(this string str)
{
bool defaultValue = false;
bool converted = bool.TryParse(str, out defaultValue);
return defaultValue;
}
///
/// 字符串转换为指定格式的列表
///
///
/// 字符串内容
/// 分隔符号
///
public static List ToDelimitedList(this string value, string delimiter)
{
if (value == null)
{
return new List();
}
var output = value.Split(new string[] { delimiter }, StringSplitOptions.RemoveEmptyEntries);
return output.Select(x => (T)Convert.ChangeType(x, typeof(T))).ToList();
}
///
/// 字符串转换为指定格式的列表
///
///
/// 字符串内容
/// 分隔符号
/// 提供的转换操作
///
public static List ToDelimitedList(this string value, string delimiter, Func converter)
{
if (value == null)
{
return new List();
}
var output = value.Split(new string[] { delimiter }, StringSplitOptions.RemoveEmptyEntries);
return output.Select(converter).ToList();
}
///
/// 根据长度分割不同的字符串到列表里面
///
/// 字符串内容
/// 分割的长度
///
public static IEnumerable SplitEvery(this string value, int length)
{
int index = 0;
while (index + length < value.Length)
{
yield return value.Substring(index, length);
index += length;
}
if (index < value.Length)
yield return value.Substring(index, value.Length - index);
}
#endregion
#region 其他辅助方法
///
/// true, if is valid email address
///
/// email address to test
/// true, if is valid email address
public static bool IsValidEmailAddress(this string s)
{
return new Regex(@"^[\w-\.]+@([\w-]+\.)+[\w-]{2,6}$").IsMatch(s);
}
///
/// Checks if url is valid.
///
///
///
public static bool IsValidUrl(this string url)
{
string strRegex = "^(https?://)"
+ "?(([0-9a-z_!~*'().&=+$%-]+: )?[0-9a-z_!~*'().&=+$%-]+@)?" //user@
+ @"(([0-9]{1,3}\.){3}[0-9]{1,3}" // IP- 199.194.52.184
+ "|" // allows either IP or domain
+ @"([0-9a-z_!~*'()-]+\.)*" // tertiary domain(s)- www.
+ @"([0-9a-z][0-9a-z-]{0,61})?[0-9a-z]" // second level domain
+ @"(\.[a-z]{2,6})?)" // first level domain- .com or .museum is optional
+ "(:[0-9]{1,5})?" // port number- :80
+ "((/?)|" // a slash isn't required if there is no file name
+ "(/[0-9a-z_!~*'().;?:@&=+$,%#-]+)+/?)$";
return new Regex(strRegex).IsMatch(url);
}
///
/// Check if url (http) is available.
///
/// url to check
///
/// string url = "www.codeproject.com;
/// if( !url.UrlAvailable())
/// ...codeproject is not available
///
/// true if available
public static bool UrlAvailable(this string httpUrl)
{
if (!httpUrl.StartsWith("http://") || !httpUrl.StartsWith("https://"))
httpUrl = "http://" + httpUrl;
try
{
HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(httpUrl);
myRequest.Method = "GET";
myRequest.ContentType = "application/x-www-form-urlencoded";
HttpWebResponse myHttpWebResponse = (HttpWebResponse)myRequest.GetResponse();
return true;
}
catch
{
return false;
}
}
///
/// Reverse the string
///
///
///
public static string Reverse(this string input)
{
char[] chars = input.ToCharArray();
Array.Reverse(chars);
return new String(chars);
}
///
/// Reduce string to shorter preview which is optionally ended by some string (...).
///
/// string to reduce
/// Length of returned string including endings.
/// optional edings of reduced text
///
/// string description = "This is very long description of something";
/// string preview = description.Reduce(20,"...");
/// produce -> "This is very long..."
///
///
public static string Reduce(this string s, int count, string endings)
{
if (count < endings.Length)
throw new Exception("Failed to reduce to less then endings length.");
int sLength = s.Length;
int len = sLength;
if (endings != null)
len += endings.Length;
if (count > sLength)
return s; //it's too short to reduce
s = s.Substring(0, sLength - len + count);
if (endings != null)
s += endings;
return s;
}
///
/// remove white space, not line end
/// Useful when parsing user input such phone,
/// price int.Parse("1 000 000".RemoveSpaces(),.....
///
///
/// string without spaces
public static string RemoveSpaces(this string s)
{
return s.Replace(" ", "");
}
///
/// true, if the string can be parse as Double respective Int32
/// Spaces are not considred.
///
/// input string
/// true, if Double is considered,
/// otherwhise Int32 is considered.
/// true, if the string contains only digits or float-point
public static bool IsNumber(this string s, bool floatpoint)
{
int i;
double d;
string withoutWhiteSpace = s.RemoveSpaces();
if (floatpoint)
{
return double.TryParse(withoutWhiteSpace, NumberStyles.Any,
Thread.CurrentThread.CurrentUICulture, out d);
}
else
{
return int.TryParse(withoutWhiteSpace, out i);
}
}
///
/// true, if the string contains only digits or float-point.
/// Spaces are not considred.
///
/// input string
/// true, if float-point is considered
/// true, if the string contains only digits or float-point
public static bool IsNumberOnly(this string s, bool floatpoint)
{
s = s.Trim();
if (s.Length == 0)
return false;
foreach (char c in s)
{
if (!char.IsDigit(c))
{
if (floatpoint && (c == '.' || c == ','))
continue;
return false;
}
}
return true;
}
///
/// Remove accent from strings
///
///
/// input: "Příliš žluťoučký kůň úpěl ďábelské ódy."
/// result: "Prilis zlutoucky kun upel dabelske ody."
///
///
/// founded at http://stackoverflow.com/questions/249087/
/// how-do-i-remove-diacritics-accents-from-a-string-in-net
/// string without accents
public static string RemoveDiacritics(this string s)
{
string stFormD = s.Normalize(NormalizationForm.FormD);
StringBuilder sb = new StringBuilder();
for (int ich = 0; ich < stFormD.Length; ich++)
{
UnicodeCategory uc = CharUnicodeInfo.GetUnicodeCategory(stFormD[ich]);
if (uc != UnicodeCategory.NonSpacingMark)
{
sb.Append(stFormD[ich]);
}
}
return (sb.ToString().Normalize(NormalizationForm.FormC));
}
///
/// Replace \r\n or \n by
///
///
///
public static string Nl2Br(this string s)
{
return s.Replace("\r\n", "
").Replace("\n", "
");
}
static MD5CryptoServiceProvider s_md5 = null;
///
/// 使用MD5加密字符串
///
/// 输入字符串
///
public static string MD5(this string s)
{
if (s_md5 == null) //creating only when needed
s_md5 = new MD5CryptoServiceProvider();
Byte[] newdata = Encoding.Default.GetBytes(s);
Byte[] encrypted = s_md5.ComputeHash(newdata);
return BitConverter.ToString(encrypted).Replace("-", "").ToLower();
}
#endregion
}
}