using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace Common
{
public static class StringExtension
{
///
/// 字符空判断
///
///
///
public static bool IsEmpty(this string str)
{
if (string.IsNullOrEmpty(str))
return true;
return false;
}
///
/// 直接格式化字符串
///
///
///
///
public static string FormatMe(this string str, params object[] args)
{
return string.Format(str, args);
}
///
/// 转化为32位int
///
///
///
public static int TryToInt32(this string str)
{
return Int32.Parse(str);
}
///
/// 转换时间
///
///
///
public static DateTime ToDateTime(this string str)
{
return DateTime.Parse(str);
}
///
/// MD5加密
///
/// 加密字符串
/// 随机加密码
///
public static string GetMD5(this string str, string salt)
{
MD5 md5 = new MD5CryptoServiceProvider();
byte[] fromData = System.Text.Encoding.Unicode.GetBytes(str + salt);
byte[] targetData = md5.ComputeHash(fromData);
string byte2String = null;
for (int i = 0; i < targetData.Length; i++)
{
byte2String += targetData[i].ToString("x");
}
return byte2String;
}
///
/// 将对象转换为Int32类型,转换失败返回0
///
/// 要转换的字符串
/// 转换后的int类型结果
public static int StrToInt(this string str)
{
return StrToInt(str, 0);
}
///
/// 将对象转换为Int32类型
///
/// 要转换的字符串
/// 缺省值
/// 转换后的int类型结果
public static int StrToInt(this string str, int defValue)
{
if (string.IsNullOrEmpty(str) || str.Trim().Length >= 11 || !Regex.IsMatch(str.Trim(), @"^([-]|[0-9])[0-9]*(\.\w*)?$"))
return defValue;
int rv;
if (Int32.TryParse(str, out rv))
return rv;
return Convert.ToInt32(StrToFloat(str, defValue));
}
///
/// string型转换为float型
///
/// 要转换的字符串
/// 缺省值
/// 转换后的int类型结果
public static float StrToFloat(this string strValue, float defValue)
{
if ((strValue == null) || (strValue.Length > 10))
return defValue;
float intValue = defValue;
if (strValue != null)
{
bool IsFloat = Regex.IsMatch(strValue, @"^([-]|[0-9])[0-9]*(\.\w*)?$");
if (IsFloat)
float.TryParse(strValue, out intValue);
}
return intValue;
}
///
/// 把特定字符删除
///
///
///
///
public static string RemoveValue(this string value, string zf= "zx95")
{
return value.Replace(zf, "");
}
///
/// 值是否是存在枚举中
///
///
///
///
public static bool IsEnum(this string value)
where T : struct
{
T a;
if (Enum.TryParse(value, out a))
{
return true;
}
return false;
}
}
}