扩展了一些String常用的方法.
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常用的方法.的更多相关文章
- String常用使用方法,1.创建string的常用3+1种方式,2.引用类型使用==比较地址值,3.String当中获取相关的常用方法,4.字符串的截取方法,5.String转换常用方法,6.切割字符串----java
一个知识点使用一个代码块方便查看 1.创建string的常用3+1种方式 /* 创建string的常用3+1种方式 三种构造方法 public String():创建一个空字符串,不含有任何内容: p ...
- String常用的方法
l String: 字符串类,字符串是常量:它们的值在创建之后不能更改 l 方法 boolean equals(Object obj) 判断两个字符串中的内容是否相同 boolean equalsIg ...
- String常用处理方法
1.去空格 用于删除字符串的头尾空白符. 语法:public String trim() 返回值:删除头尾空白符的字符串. 删除所有空格 str.replace(" ", &quo ...
- String对象中常用的方法
String对象中常用的方法 1.charCodeAt方法返回一个整数,代表指定位置字符的Unicode编码.strObj.charCodeAt(index)说明:index将被处理字符的从零开始 ...
- js中关于string的一些常用的方法
最近总结了一些关于string中的常用方法, 其中大部分的方法来自于<JavaScript框架设计>这本书, 如果有更好的方法,或者有关于string的别的常用的方法,希望大家不吝赐教. ...
- String:(字符串)中常用的方法
package stringyiwen; //字符串中常用的方法public class StringTest03 { public static void main(String[] args) { ...
- String类中常用的方法
@Test public void demo(){ // 以下为String中的常用的方法及注释, 最常用的注释前有**标注 String s = "abcdefg123456"; ...
- int转换为String,常用的四种方法。
int i = 100; 方法一:String s1 = i + " "; 方法二:String s2 = String.valueof(i); 方法三(先转换为Integer类型 ...
- jQuery常用工具方法
前面的话 jQuery提供一些与元素无关的工具方法,不必选中元素,就可以直接使用这些方法.如果理解原生javascript的继承原理,那么就能理解工具方法的实质.它是定义在jQuery构造函数上的方法 ...
随机推荐
- centos7 防火墙问题
centos从7开始默认用的是firewalld,这个是基于iptables的,虽然有iptables的核心,但是iptables的服务是没安装的.所以你只要停止firewalld服务即可:sudo ...
- 获取bing图片并自动设置为电脑桌面背景(使用 URLDownloadToFile API函数)
众所周知,bing搜索网站首页每日会更新一张图片,张张漂亮(额,也有一些不合我口味的),特别适合用来做电脑壁纸. 我们想要将bing网站背景图片设置为电脑桌面背景的通常做法是: 上网,搜索bing 找 ...
- Android零基础入门第25节:最简单最常用的LinearLayout线性布局
原文:Android零基础入门第25节:最简单最常用的LinearLayout线性布局 良好的布局设计对于UI界面至关重要,在前面也简单介绍过,目前Android中的布局主要有6种,创建的布局文件默认 ...
- 关于DexOpt: not all deps represented
最近在做android BSP 4.2的时候遇到一个BUG,编译user 版本的时候,系统刷进手机里面去,无限循环在开机动画,编译userdebug 刷机进去的时候发现正常,于是我先回滚到正常的版本, ...
- nltk处理文本
nltk(Natural Language Toolkit)是处理文本的利器. 安装 pip install nltk 进入python命令行,键入nltk.download()可以下载nltk需要的 ...
- “真正的工作不是说的天花乱坠”,Torvalds 说, “而是在于细节”(Torvalds 认为成功的项目都是99%的汗水和1%的创新)
在刚刚结束的加利福尼亚州的开源领袖峰会(2月14日-16日)上,Linus Torvalds 接受了外媒的采访,分享了他如何管理 Linux kernel 的开发以及他对工作的态度. “真正的工作不是 ...
- DELPHI之关于String的内存分配(引)
在函数.过程或者方法中定义一个字符串变量时,由于我们知道在函数.过程或者方法中定义的变量为局部变量,它的内存 是在栈中分配的,但是这里有个小细节我们要注意,对于一个局部的字符串变量,它的大小为4字节, ...
- Qt加载百度离线地图
1.下载百度地图离线API 1.3 下载链接:http://download.csdn.NET/detail/caoshangpa/9476608,网上虽然出现了2.0版本离线API,但是经试用,存在 ...
- 去除文件属性(使用SetFileAttributes API函数)
FILE_ATTRIBUTE_ARCHIVE 文件存档(备份或移动时会对文件做标记).FILE_ATTRIBUTE_ENCRYPTED 加密(对文件来说是内容加密,对目录来说是对将来新建的文件默认为加 ...
- C#每天进步一点--事件
事件:如果类型定义了事件成员,那么类型就可以通知其他对象发生了特定的事情.例如,Button类提供了一个名为Click的事件.应用程序中的一个或者多个对象可能想接收关于这个事件的通知,以便在Butto ...