using System;
using System.Diagnostics;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions; namespace Taolx.JuneAir.Common.Extensions
{ /// <summary>
/// String 扩展类
/// </summary>
public static class StringExtension
{
private static readonly Regex WebUrlExpression = new Regex(@"(http|https)://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?", RegexOptions.Singleline | RegexOptions.Compiled);
private static readonly Regex EmailExpression = new Regex(@"^([0-9a-zA-Z]+[-._+&])*[0-9a-zA-Z]+@([-0-9a-zA-Z]+[.])+[a-zA-Z]{2,6}$", RegexOptions.Singleline | RegexOptions.Compiled);
private static readonly Regex StripHTMLExpression = new Regex("<\\S[^><]*>", RegexOptions.IgnoreCase | RegexOptions.Singleline | RegexOptions.Multiline | RegexOptions.CultureInvariant | RegexOptions.Compiled);
private static readonly char[] IllegalUrlCharacters = new[] { ';', '/', '\\', '?', ':', '@', '&', '=', '+', '$', ',', '<', '>', '#', '%', '.', '!', '*', '\'', '"', '(', ')', '[', ']', '{', '}', '|', '^', '`', '~', '–', '‘', '’', '“', '”', '»', '«' };
/// <summary>
/// 默认密钥-密钥的长度必须是32
/// </summary>
private const string PublicKey = "1qaz2wsx3edc4rfv"; /// <summary>
/// 默认向量
/// </summary>
private const string Iv = "abcdefghijklmnop"; /// <summary>
/// 为空或者""
/// </summary>
/// <param name="source"></param>
/// <returns></returns>
public static bool IsNullOrEmpty(this string source)
{
return string.IsNullOrEmpty(source);
} /// <summary>
/// ToTrim
/// </summary>
/// <param name="source"></param>
/// <param name="defalutVal"></param>
/// <returns></returns>
public static string ToTrim(this string source, string defalutVal = "")
{
return (source ?? defalutVal).Trim();
} /// <summary>
/// string类型日期转换成datetiem类型
/// </summary>
/// <param name="str"></param>
/// <returns>转换失败返回null</returns>
public static DateTime? ToNullbaleDateTime(this string str)
{
if (string.IsNullOrEmpty(str))
return null;
DateTime dateTime;
return DateTime.TryParse(str, out dateTime) ? dateTime : (DateTime?)null;
} /// <summary>
/// 将当前字符串从指定索引位置将指定长度的字符替换为新字符
/// </summary>
/// <param name="oldStr">当前字符串</param>
/// <param name="index">替换起始索引位置</param>
/// <param name="length">指定长度</param>
/// <param name="newChar">替换的字符</param>
/// <returns></returns>
public static string ReplaceStr(this string oldStr, int index, int length, char newChar = '*')
{
if (oldStr == null)
return "";
if (index < )
index = ;
if (length > oldStr.Length)
length = oldStr.Length;
string keepStr = oldStr.Substring(length - index, oldStr.Length - length);
return keepStr.PadLeft(oldStr.Length, newChar);
} /// <summary>
/// 获取32位长度的Md5摘要
/// </summary>
/// <param name="input"></param>
/// <param name="encoding"></param>
/// <returns></returns>
public static string Get32Md5(this string input, Encoding encoding = null)
{
if (encoding == null) encoding = Encoding.UTF8;
StringBuilder buff = new StringBuilder();
MD5 md5 = new MD5CryptoServiceProvider();
byte[] t = md5.ComputeHash(encoding.GetBytes(input));
foreach (byte t1 in t)
buff.Append(t1.ToString("x").PadLeft(, ''));
return buff.ToString();
} /// <summary>
/// md5去掉"-"转成string
/// </summary>
public static string ToMD5(this string str)
{
//return System.Security.Cryptography.MD5.Create(str).ToString();
//return FormsAuthentication.HashPasswordForStoringInConfigFile(str, "MD5"); //System.Security.Cryptography.MD5 md55 = new System.Security.Cryptography.MD5CryptoServiceProvider(); if (string.IsNullOrEmpty(str)) return str;
System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create();
string encoded = BitConverter.ToString(md5.ComputeHash(Encoding.UTF8.GetBytes(str))).Replace("-", "");
return encoded.ToLower();
} /// <summary>
/// 是否为WebUrl地址
/// </summary>
/// <param name="target"></param>
/// <returns></returns>
public static bool IsWebUrl(this string target)
{
return !string.IsNullOrEmpty(target) && WebUrlExpression.IsMatch(target);
} /// <summary>
/// 是否为Email地址
/// </summary>
/// <param name="target"></param>
/// <returns></returns>
public static bool IsEmail(this string target)
{
return !string.IsNullOrEmpty(target) && EmailExpression.IsMatch(target);
} /// <summary>
/// string转Guid
/// </summary>
/// <param name="target"></param>
/// <returns></returns>
public static Guid ToGuid(this string target)
{
Guid result = Guid.Empty; if ((!string.IsNullOrEmpty(target)) && (target.Trim().Length == ))
{
string encoded = string.Concat(target.Trim().Replace("-", "+").Replace("_", "/"), "=="); try
{
byte[] base64 = Convert.FromBase64String(encoded); result = new Guid(base64);
}
catch (FormatException)
{
}
} return result;
} /// <summary>
/// 是否为数字
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static Boolean IsNumeric(this String str)
{
long temp_big_int;
var is_number = long.TryParse(str, out temp_big_int);
return is_number;
} /// <summary>
/// string to int
/// </summary>
/// <param name="str"></param>
/// <param name="defVal"></param>
/// <returns></returns>
public static int ToInt(this String str, int defVal = )
{
int.TryParse(str, out defVal);
return defVal;
} /// <summary>
/// string to long
/// </summary>
/// <param name="str"></param>
/// <param name="defVal"></param>
/// <returns></returns>
public static long ToLong(this String str, long defVal = )
{
long.TryParse(str, out defVal);
return defVal;
} /// <summary>
/// string to decimal
/// </summary>
/// <param name="str"></param>
/// <param name="defVal"></param>
/// <returns></returns>
public static decimal ToDecimal(this String str, decimal defVal = )
{
decimal.TryParse(str, out defVal);
return defVal;
} /// <summary>
/// string to float
/// </summary>
/// <param name="str"></param>
/// <param name="defVal"></param>
/// <returns></returns>
public static float ToFloat(this String str, float defVal = )
{
float.TryParse(str, out defVal);
return defVal;
} /// <summary>
/// string to double
/// </summary>
/// <param name="str"></param>
/// <param name="defVal"></param>
/// <returns></returns>
public static double ToDouble(this String str, double defVal = )
{
double.TryParse(str, out defVal);
return defVal;
} private static DateTime minValue = DateTime.MinValue; /// <summary>
/// string to datetime
/// </summary>
/// <param name="str"></param>
/// <param name="format">日期格式</param>
/// <param name="defVal">默认日期</param>
/// <returns></returns>
public static DateTime ToDateTime(this string str, string format, DateTime defVal)
{
try
{
DateTime dt = DateTime.ParseExact(str, format, System.Globalization.CultureInfo.InvariantCulture);
return dt;
}
catch (Exception ex)
{
Debug.WriteLine(ex);
return defVal;
}
} #region 加解密
/// <summary>
/// AES加密
/// </summary>
/// <param name="str">需要加密字符串</param>
/// <returns>加密后字符串</returns>
public static String Encrypt(this string str)
{
try
{
return Encrypt(str, PublicKey);
}
catch (Exception e)
{
return str;
}
} /// <summary>
/// AES解密
/// </summary>
/// <param name="str">需要解密字符串</param>
/// <returns>解密后字符串</returns>
public static String Decrypt(this string str)
{
try
{
return Decrypt(str, PublicKey);
}
catch (Exception e)
{
return str;
}
}
/// <summary>
/// AES加密
/// </summary>
/// <param name="str">需要加密的字符串</param>
/// <param name="key">32位密钥</param>
/// <returns>加密后的字符串</returns>
public static string Encrypt(this string str, string key)
{
Byte[] keyArray = System.Text.Encoding.UTF8.GetBytes(key);
Byte[] toEncryptArray = System.Text.Encoding.UTF8.GetBytes(str);
var rijndael = new System.Security.Cryptography.RijndaelManaged();
rijndael.Key = keyArray;
rijndael.Mode = System.Security.Cryptography.CipherMode.ECB;
rijndael.Padding = System.Security.Cryptography.PaddingMode.PKCS7;
rijndael.IV = System.Text.Encoding.UTF8.GetBytes(Iv);
System.Security.Cryptography.ICryptoTransform cTransform = rijndael.CreateEncryptor();
Byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, , toEncryptArray.Length);
return Convert.ToBase64String(resultArray, , resultArray.Length);
}
/// <summary>
/// AES解密
/// </summary>
/// <param name="str">需要解密的字符串</param>
/// <param name="key">32位密钥</param>
/// <returns>解密后的字符串</returns>
public static string Decrypt(this string str, string key)
{
Byte[] keyArray = System.Text.Encoding.UTF8.GetBytes(key);
Byte[] toEncryptArray = Convert.FromBase64String(str);
var rijndael = new System.Security.Cryptography.RijndaelManaged();
rijndael.Key = keyArray;
rijndael.Mode = System.Security.Cryptography.CipherMode.ECB;
rijndael.Padding = System.Security.Cryptography.PaddingMode.PKCS7;
rijndael.IV = System.Text.Encoding.UTF8.GetBytes(Iv);
System.Security.Cryptography.ICryptoTransform cTransform = rijndael.CreateDecryptor();
Byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, , toEncryptArray.Length);
return System.Text.Encoding.UTF8.GetString(resultArray);
}
/// <summary>
/// AES加密
/// </summary>
/// <param name="str">需要加密字符串</param>
/// <returns>加密后字符串</returns>
public static String EncryptToString(this string str)
{
try
{
return EncryptToString(str, PublicKey);
}
catch (Exception e)
{
return str;
}
} /// <summary>
/// AES加密
/// </summary>
/// <param name="str">需要加密的字符串</param>
/// <param name="key">32位密钥</param>
/// <returns>加密后的字符串</returns>
public static string EncryptToString(this string str, string key)
{
Byte[] keyArray = System.Text.Encoding.UTF8.GetBytes(key);
Byte[] toEncryptArray = System.Text.Encoding.UTF8.GetBytes(str);
var rijndael = new System.Security.Cryptography.RijndaelManaged();
rijndael.Key = keyArray;
rijndael.Mode = System.Security.Cryptography.CipherMode.ECB;
rijndael.Padding = System.Security.Cryptography.PaddingMode.PKCS7;
rijndael.IV = System.Text.Encoding.UTF8.GetBytes(Iv);
System.Security.Cryptography.ICryptoTransform cTransform = rijndael.CreateEncryptor();
Byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, , toEncryptArray.Length);
StringBuilder builder = new StringBuilder();
int num2 = resultArray.Length - ;
for (int i = ; i <= num2; i++)
{
builder.AppendFormat("{0:X2}", resultArray[i]);
}
return builder.ToString();
// return Convert.ToBase64String(resultArray, 0, resultArray.Length);
} /// <summary>
/// AES解密
/// </summary>
/// <param name="str">需要解密字符串</param>
/// <returns>解密后字符串</returns>
public static String DecryptToString(this string str)
{
try
{
return DecryptToString(str, PublicKey);
}
catch (Exception e)
{
return str;
}
} /// <summary>
/// AES解密
/// </summary>
/// <param name="str">需要解密的字符串</param>
/// <param name="key">32位密钥</param>
/// <returns>解密后的字符串</returns>
public static string DecryptToString(this string str, string key)
{
Byte[] keyArray = System.Text.Encoding.UTF8.GetBytes(key);
int halfInputLength = str.Length / ;
Byte[] toEncryptArray = new Byte[halfInputLength];
for (int x = ; x < halfInputLength; x++)
{
int i = (Convert.ToInt32(str.Substring(x * , ), ));
toEncryptArray[x] = (byte)i;
} var rijndael = new System.Security.Cryptography.RijndaelManaged();
rijndael.Key = keyArray;
rijndael.Mode = System.Security.Cryptography.CipherMode.ECB;
rijndael.Padding = System.Security.Cryptography.PaddingMode.PKCS7;
rijndael.IV = System.Text.Encoding.UTF8.GetBytes(Iv);
System.Security.Cryptography.ICryptoTransform cTransform = rijndael.CreateDecryptor();
Byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, , toEncryptArray.Length);
return System.Text.Encoding.UTF8.GetString(resultArray);
// return UTF8Encoding.UTF8.GetString(resultArray);
}
#endregion private static readonly Regex RepalceHttpToHttpsRegex = new Regex("^http(\\:\\/\\/){1}", RegexOptions.IgnoreCase);
/// <summary>
/// 替换http为https
/// </summary>
/// <param name="url">targetProtocol: https</param>
/// <returns></returns>
public static string ToHttpsUrl(this string url)
{
url = url.ToTrim();
string strOutput = RepalceHttpToHttpsRegex.Replace(url, "https://");
return strOutput;
} private static readonly Regex RemoveHttpOrHttpsRegex = new Regex("^http(s?)(\\:\\/\\/){1}", RegexOptions.IgnoreCase);
/// <summary>
////// </summary>
/// <param name="url">targetProtocol: https</param>
/// <returns></returns>
public static string ToRemoveUrlProtocol(this string url)
{
url = url.ToTrim();
string strOutput = RemoveHttpOrHttpsRegex.Replace(url, "//");
return strOutput;
}
}
}

扩展了一些String常用的方法.的更多相关文章

  1. String常用使用方法,1.创建string的常用3+1种方式,2.引用类型使用==比较地址值,3.String当中获取相关的常用方法,4.字符串的截取方法,5.String转换常用方法,6.切割字符串----java

    一个知识点使用一个代码块方便查看 1.创建string的常用3+1种方式 /* 创建string的常用3+1种方式 三种构造方法 public String():创建一个空字符串,不含有任何内容: p ...

  2. String常用的方法

    l String: 字符串类,字符串是常量:它们的值在创建之后不能更改 l 方法 boolean equals(Object obj) 判断两个字符串中的内容是否相同 boolean equalsIg ...

  3. String常用处理方法

    1.去空格 用于删除字符串的头尾空白符. 语法:public String trim() 返回值:删除头尾空白符的字符串. 删除所有空格 str.replace(" ", &quo ...

  4. String对象中常用的方法

    String对象中常用的方法   1.charCodeAt方法返回一个整数,代表指定位置字符的Unicode编码.strObj.charCodeAt(index)说明:index将被处理字符的从零开始 ...

  5. js中关于string的一些常用的方法

    最近总结了一些关于string中的常用方法, 其中大部分的方法来自于<JavaScript框架设计>这本书, 如果有更好的方法,或者有关于string的别的常用的方法,希望大家不吝赐教. ...

  6. String:(字符串)中常用的方法

    package stringyiwen; //字符串中常用的方法public class StringTest03 { public static void main(String[] args) { ...

  7. String类中常用的方法

    @Test public void demo(){ // 以下为String中的常用的方法及注释, 最常用的注释前有**标注 String s = "abcdefg123456"; ...

  8. int转换为String,常用的四种方法。

    int i = 100; 方法一:String s1 = i + " "; 方法二:String s2 = String.valueof(i); 方法三(先转换为Integer类型 ...

  9. jQuery常用工具方法

    前面的话 jQuery提供一些与元素无关的工具方法,不必选中元素,就可以直接使用这些方法.如果理解原生javascript的继承原理,那么就能理解工具方法的实质.它是定义在jQuery构造函数上的方法 ...

随机推荐

  1. MVC EF 导航属性

    @model IQueryable<EFExam.Models.CategoryProductViewModel>@{    Layout = null;}<!DOCTYPE htm ...

  2. iOS UIScrollView使用Autolayout

    最近项目在迭代更新的时候,需要在之前用Autolayout写的界面里添加一个button,添加完这个button后,iPhone5,iPhone4显示不全了.遇到整个问题后很自然就想到了用UIScro ...

  3. 算法之--回溯法-迷宫问题【python实现】

    题目描述 定义一个二维数组N*M(其中2<=N<=10;2<=M<=10),如5 × 5数组下所示: int maze[5][5] = { 0, 1, 0, 0, 0, 0,  ...

  4. tf.nn.softmax & tf.nn.reduce_sum & tf.nn.softmax_cross_entropy_with_logits

    tf.nn.softmax softmax是神经网络的最后一层将实数空间映射到概率空间的常用方法,公式如下: \[ softmax(x)_i=\frac{exp(x_i)}{\sum_jexp(x_j ...

  5. 使用mingw 对libcURL,openSSL,zLib交叉编译

    使用mingw 对libcURL,openSSL,zLib交叉编译   将三个库解压到同一目录下 比如取目录名为 "source" 的目录   提前安装active-perl 配置 ...

  6. Qt 5.6.0 动态编译(VS2013 x86 target xp openssl icu webkit)

    经历了多次延期后,在3月16号,Qt发布了5.6.0版本(全面支持高DPI无疑是一个亮点),从5.6.0版本开始,Qt直接移除了webkit模块,让webengine作为其替代选择,不过webengi ...

  7. Hadoop 3、Hadoop 分布式存储系统 HDFS(好多彩色图)

    HDFS是Hadoop Distribute File System 的简称,也就是Hadoop的一个分布式文件系统. 一.HDFS的优缺点 1.HDFS优点: a.高容错性 .数据保存多个副本 .数 ...

  8. Kafka笔记7

    Kafka提供了一些命令行工具,用于管理集群变更.这些工具使用Java实现,Kafka提供了一些脚本调用这些Java类. 9.1主题操作 使用Kafka-topics.sh工具可以执行主题大部分工作, ...

  9. l论文查重平台

    推荐大家一个靠谱的论文检测平台.重复的部分有详细出处以及具体修改意见,能直接在文章上做修改,全部改完一键下载就搞定了.怕麻烦的话,还能用它自带的降重功能.哦对了,他们现在正在做毕业季活动, 赠送很多免 ...

  10. 【Mysql】重启: mysql.service: Service hold-off time over, scheduling restart.

    参考链接:http://sharong.iteye.com/blog/2262760 重启mysql服务器 (/etc/init.d/mysql stop  /etc/init.d/mysql sta ...