【转】字符串处理函数总结
在网上看到或平时工作中使用的字符串处理函数,现总结一下,如果大家有好的补充一下:
1、是否为空:
public static bool IsEmpty(this string input)
{
if (input == null || input.Trim().Length == 0)
return true;
return false;
}
2、加密:
public static string MD5(this string input)
{
string returnValue = string.Empty;
byte[] inputBytes = Encoding.UTF8.GetBytes(input);
MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
byte[] resultBytes = md5.ComputeHash(inputBytes);
foreach (byte b in resultBytes)
returnValue += b.ToString("X").PadLeft(2, '0');
md5.Clear();
return returnValue;
}
/// <summary>
/// RijndaelManaged加密
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public static string Encrypt(this string input)
{
if (input.IsEmpty())
return string.Empty;
return BaseEncrypt.Encrypt(input);
}
/// <summary>
/// 解密RijndaelManaged加密字符串
/// </summary>
/// <param name="input"></param>
/// <param name="originalText">解密后的明文字符串</param>
/// <returns></returns>
public static string Decrypt(this string input)
{
if (input.IsEmpty())
return string.Empty;
try
{
return BaseEncrypt.Decrypt(input);
}
catch { }
return string.Empty;
}
/// <summary>
/// 带时间戳的RijndaelManaged加密
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public static string EncyptWithTime(this string input)
{
if (input.IsEmpty())
return string.Empty;
int l = input.Length;
string time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
Random rnd = new Random();
int P = rnd.Next(l);
input = input.Insert(P, time);
input = input.Encrypt();
input += string.Format("^{0}", P);
return input.Encrypt();
}
/// <summary>
/// 解密带时间戳的RijndaelManaged的加密串
/// </summary>
/// <param name="input"></param>
/// <param name="originalText">解密后的明文字符串</param>
/// <param name="time">时间戳</param>
/// <returns></returns>
public static bool TryDecryptWithTime(this string input, out string text, out DateTime time)
{
text = string.Empty;
time = DateTime.MinValue;
if (!(text = input.Decrypt()).IsEmpty())
{
int position = text.LastIndexOf('^');
if (position != -1)
{
int P = text.Substring(position + 1).ParseTo<int>();
if (P > 0)
{
text = text.Substring(0, position);
if (!(text = text.Decrypt()).IsEmpty())
{
time = text.Substring(P, 19).ParseTo<DateTime>();
text = text.Substring(0, P) + text.Substring(P + 19);
return true;
}
}
}
}
return false;
}
3、RijndaelManaged的加密用到的一个静态类
public static class BaseEncrypt
{
private static byte[] iv = null;
private static byte[] key = null;
private static RijndaelManaged rm = new RijndaelManaged();
static BaseEncrypt()
{
string str_iv = ConfigurationManager.AppSettings["sys_EncryptIV"];
string str_key = ConfigurationManager.AppSettings["sys_EncryptKey"];
if (str_iv.Length() != 16)
str_iv = "&^q)@Mbl%s!2~8d#";
if (str_key.Length() != 32)
str_key = ")(*jJ6%y$^7s%#rap#sm&%$;j/a'1s]|";
iv = Encoding.ASCII.GetBytes(str_iv);
key = Encoding.ASCII.GetBytes(str_key);
}
public static string Encrypt(string input)
{
byte[] inputArr = Encoding.Default.GetBytes(input);
rm.IV = iv;
rm.Key = key;
ICryptoTransform ict = rm.CreateEncryptor();= new MemoryStream();
CryptoStream crypt = new CryptoStream(memory, ict, CryptoStreamMode.Write);
crypt.Write(inputArr, 0, inputArr.Length);
crypt.FlushFinalBlock();
byte[] _Result = memory.ToArray();
memory.Close();
return Convert.ToBase64String(_Result);
}
public static string Decrypt(string input)
{
byte[] _Input = Convert.FromBase64String(input);
MemoryStream _Memory = new MemoryStream(_Input, 0, _Input.Length);
rm.IV = iv;
rm.Key = key;
ICryptoTransform ict = rm.CreateDecryptor();
CryptoStream crypt = new CryptoStream(_Memory, ict, CryptoStreamMode.Read);
StreamReader sr = new StreamReader(crypt);
return sr.ReadToEnd();
}
}
4、表现层基类:
MemoryStream memory
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;
using System.Text.RegularExpressions;
namespace Website
{
/// <summary>
/// 页面层(表示层)基类,所有页面继承该页面
/// </summary>
public class PageBase : System.Web.UI.Page
{
public PageBase()
{
//
// TODO: 在此处添加构造函数逻辑
//
}
#region 客户端脚本(javascript)
/// <summary>
/// 客户端脚本(javascript)消息框(alert)
/// </summary>
public void ClientScriptAlert(string message)
{
message = message.Replace("/"", "///"").Replace("/n", "///n").Replace("/r", "///r");
string jsText = string.Format("alert(/"{0}/");", message);
ClientJavaScript(jsText);
}
/// <summary>
/// 客户端脚本(javascript)消息框(alert),并跳转页面
/// </summary>
public void ClientScriptAlert(string message, string url)
{
message = message.Replace("/"", "///"").Replace("/n", "///n").Replace("/r", "///r");
string scriptText = string.Format("alert(/"{0}/");window.location=/"{1}/";", message, url);
ClientJavaScript(scriptText);
//this.Response.Write(string.Format("<script type=/"text/javascript/" language=/"javascript/">{0}</script>", scriptText));
//this.Response.End();
}
/// <summary>
/// 客户端脚本(javascript)
/// </summary>
public void ClientJavaScript(string scriptText)
{
string scriptKey = "ClientScript";
int index = 1;
while (this.ClientScript.IsStartupScriptRegistered(this.GetType(), scriptKey + index.ToString()))
{
index++;
}
scriptText = string.Format("<script type=/"text/javascript/" language=/"javascript/">{0}</script>", scriptText);
//RegisterStartupScript(scriptKey + index.ToString(), scriptText);
this.ClientScript.RegisterStartupScript(this.GetType(), scriptKey + index.ToString(), scriptText);
}
#endregion
/// <summary>
/// 截取指定长度字符串,一个中文两个字节
/// </summary>
public string SubString(object value, int len)
{
return SubString(Convert.ToString(value), len);
}
/// <summary>
/// 截取指定长度字符串,一个中文两个字节
/// </summary>
public string SubString(string value, int len)
{
return Common.Common.SubString(value, len);
}
/// <summary>
/// 日期转为指定格式字符串
/// </summary>
public string DateTimeToString(object value, string format)
{
if (value != null && value != DBNull.Value)
{
try
{
return Convert.ToDateTime(value).ToString(format);
}
catch { }
}
return string.Empty;
}
/// <summary>
/// 对字符串进行 HTML 编码并返回已编码的字符串。
/// </summary>
public string HtmlEncode(object value)
{
if (value == null || value == DBNull.Value) return string.Empty;
return HtmlEncode(value.ToString());
}
/// <summary>
/// 对字符串进行 HTML 编码并返回已编码的字符串。
/// </summary>
public string HtmlEncode(string value)
{
return HttpUtility.HtmlEncode(value);
}
/// <summary>
/// 过滤HTML中jiavascript,iframe,frameset以及事件等脚本
/// </summary>
/// <param name="html">脚本代码</param>
/// <returns>过滤后得脚本代码</returns>
public string FilterScript(string html)
{
if (string.IsNullOrEmpty(html)) return html;
Regex regex = new Regex(@"<script[/s/S]+</script *>", RegexOptions.IgnoreCase);
html = regex.Replace(html, ""); //过滤<script></script>标记
Regex regex1 = new Regex(@" href *= *[/s/S]*script *:", RegexOptions.IgnoreCase);
html = regex1.Replace(html, ""); //过滤href=javascript: (<A>) 属性
Regex regex2 = new Regex(@" on(mouseover|mouseon|mouseout|click|dblclick|blur|focus|change)*=", RegexOptions.IgnoreCase);
html = regex2.Replace(html, " _disibledevent="); //过滤其它控件的on...事件
Regex regex3 = new Regex(@"<iframe[/s/S]+</iframe *>", RegexOptions.IgnoreCase);
html = regex3.Replace(html, ""); //过滤iframe
Regex regex4 = new Regex(@"<frameset[/s/S]+</frameset *>", RegexOptions.IgnoreCase);
html = regex4.Replace(html, ""); //过滤frameset
Regex regex5 = new Regex(@"(Javascript|javascript):", RegexOptions.IgnoreCase);
html = regex5.Replace(html, ""); //过滤所有javascript
Regex regex6 = new Regex(@":*expression", RegexOptions.IgnoreCase);
html = regex6.Replace(html, ""); //过滤所有javascript
Regex regex7 = new Regex(@"<!--[/s/S]*-->", RegexOptions.IgnoreCase);
html = regex7.Replace(html, ""); //过滤所有HTML说明标签
return html;
}
#region 客户机登录windows用户帐号
/// <summary>
/// 客户机登录windows用户帐号
/// </summary>
public string GetLoginUserID()
{
string userName = string.Empty;
if (this.Session["_logonName"] != null)
{
object obj = this.Session["_logonName"];
userName = Convert.ToString(obj);
if (!string.IsNullOrEmpty(userName))
{
return userName;
}
}
userName = System.Configuration.ConfigurationManager.AppSettings.Get("LogonName");
if (!string.IsNullOrEmpty(userName))
{
this.Session["_logonName"] = userName;
return userName;
}
System.Web.UI.Page pageuser = new System.Web.UI.Page();
userName = this.User.Identity.Name.Trim();
if (!string.IsNullOrEmpty(userName))
{
string[] temp = userName.Split('//');
userName = temp[temp.Length - 1];
}
if (this != null)
{
this.Session["_logonName"] = userName;
}
return userName;
}
#endregion
/// <summary>
/// 加密url参数(QueryString)
/// </summary>
/// <param name="url">不带参数的url</param>
/// <param name="parameters">url参数集</param>
/// <returns></returns>
public string EncryptUrlQueryString(string url, System.Collections.Generic.Dictionary<string, string> parameters)
{
return url + EncryptUrlQueryString(parameters);
}
/// <summary>
/// 加密url参数(QueryString)
/// </summary>
/// <param name="url">不带参数的url</param>
/// <param name="parameters">url参数集</param>
/// <returns></returns>
public string EncryptUrlQueryString(System.Collections.Generic.Dictionary<string, string> parameters)
{
string queryString = "";
foreach (System.Collections.Generic.KeyValuePair<string, string> pair in parameters)
{
queryString += "&" + this.Server.UrlEncode(pair.Key) + "=" + this.Server.UrlEncode(pair.Value);
}
queryString = queryString.TrimStart('&');
return "?s=" + this.Server.UrlEncode(Common.Common.EncryptString(queryString));
}
/// <summary>
/// 解密url参数(QueryString)
/// </summary>
/// <returns></returns>
public System.Collections.Generic.Dictionary<string, string> DecryptUrlQueryString()
{
System.Collections.Generic.Dictionary<string, string> dir = new System.Collections.Generic.Dictionary<string, string>();
string queryString=Request.QueryString["s"];
if (!string.IsNullOrEmpty(queryString))
{
queryString = Common.Common.DecryptString(queryString);
string[] str = queryString.Split('&');
for (int i = 0; i < str.Length; i++)
{
string key = str[i].Substring(0, str[i].IndexOf("="));
string value = str[i].Replace(key + "=", "");
dir.Add(key, value);
}
}
return dir;
}
}
}
5、按字节截取字符串,结尾用指定的字符替换
/// <summary>
/// 按字节截取字符串,结尾用指定的字符替换...
/// </summary>
/// <param name="strVal">文本</param>
/// <param name="iLength">长度</param>
/// <returns>截取后的字符串</returns>
/// <remarks>全角字符占2位</remarks>
public static string CutString(string strVal, int iLength,string replaceStr)
{
int iCnt = 0;
int i_index;
int i_len;
System.Text.StringBuilder strRet = new System.Text.StringBuilder();
i_len = strVal.Length;
byte[] chrbyte;= System.Text.Encoding.Unicode;
chrbyte = encoding.GetBytes(strVal);
for (i_index = 1; i_index < (chrbyte.Length); i_index = i_index + 2)
{
iCnt++;
if (chrbyte[i_index] != 0)
{
iCnt++;
}
if (iCnt <= iLength)
{
byte[] va = new byte[2];
va[0] = chrbyte[i_index - 1];
va[1] = chrbyte[i_index];
strRet.Append(encoding.GetString(va));
}
else
{
if (i_index < chrbyte.Length + 1)
{
strRet.Append(replaceStr);
}
break;
}
}
return strRet.ToString();
}
6、ArrayList、Array与String互换:
System.Text.Encoding encoding
#region Array转化为String
/// <summary>
/// Array转化为String
/// </summary>
/// <param name="stringArray">字符串数组</param>
/// <returns></returns>
public static string ArrayToString(string[] stringArray)
{
string totalString = string.Empty;
for (int i = 0; i < stringArray.Length; i++)
{
totalString = totalString + stringArray[i];
}
return totalString;
}
#endregion
#region Array转化为String(包含分隔符)
/// <summary>
/// Array转化为String(包含分隔符)
/// </summary>
/// <param name="stringArray">字符串数组</param>
/// <param name="splitChar">分隔符</param>
/// <returns></returns>
public static string ArrayToString(string[] stringArray, string splitChar)
{
string totalString = string.Empty;
for (int i = 0; i < stringArray.Length; i++)
{
totalString = totalString + stringArray[i] + splitChar;
}
if (!totalString.Equals(string.Empty))
{
totalString = totalString.Substring(0, totalString.Length - 1);
}
return totalString;
}
#endregion
#region ArrayList转化为string类型数组
/// <summary>
/// ArrayList转化为string类型数组
/// </summary>
/// <param name="list">ArrayList对象</param>
/// <returns></returns>
public static string[] ArrayListToStringArray(ArrayList list)
{
string[] arrString = null;
return arrString = (string[])list.ToArray(typeof(string));
}
#endregion
#region string类型数组转化为ArrayList
/// <summary>
/// string类型数组转化为ArrayList
/// </summary>
/// <param name="list">string类型数组对象</param>
/// <returns></returns>
public static ArrayList StringArrayToArrayList(string[] list)
{
ArrayList aryList = new ArrayList(list);
return aryList;
}
#endregion
#region ArrayList转化为String
/// <summary>
/// ArrayList转化为String
/// </summary>
/// <param name="list">ArrayList数组对象</param>
/// <returns></returns>
public static string ArrayListToString(ArrayList list)
{
string str = string.Join("",(string[])list.ToArray(typeof(string)));
return str;
}
#endregion
#region ArrayList转化为String(包含分隔符)
/// <summary>
/// ArrayList转化为String(包含分隔符)
/// </summary>
/// <param name="list">ArrayList数组对象</param>
/// <param name="splitChar">分隔符</param>
/// <returns></returns>
public static string ArrayListToString(ArrayList list, string splitChar)
{
string str = string.Join(splitChar, (string[])list.ToArray(typeof(string)));
return str;
}
#endregion
#region String转化为ArrayList
/// <summary>
/// String转化为ArrayList
/// </summary>
/// <param name="str">字符串</param>
/// <param name="splitChar">分隔符</param>
/// <returns></returns>
public static ArrayList StringToArrayList(string str, Char splitChar)
{
if (str.IndexOf(splitChar) == -1)
{
return null;
}
ArrayList list = new ArrayList(str.Split(splitChar));
return list;
}
#endregion
7、搜索符合条件的控件:
public static class extend_System_Windows_Forms_Control
{
public delegate bool checkcontrol(System.Windows.Forms.Control contr, ref bool istargetControl);
/// <summary>
/// 搜索符合条件的控件
/// </summary>
/// <param name="container"></param>
/// <param name="checktargetcontrol">一个过滤控件的方法( bool(System.Windows.Forms.Control, ref bool) );ref bool代表控件是否符合搜索条件;如果返回值为true,则Findcontrols继续向前搜索,返回false,则Findcontrols停止搜索</param>
/// <returns>返回查找到的控件数组</returns>
public static System.Windows.Forms.Control[] Findcontrols(this System.Windows.Forms.Control container, checkcontrol checktargetcontrol)
{
List<System.Windows.Forms.Control> lis = new List<System.Windows.Forms.Control>();
foreach (System.Windows.Forms.Control contr in container.Controls)
{
bool istarget = false;
bool iscontinue = checktargetcontrol(contr, ref istarget);
if (istarget) lis.Add(contr);
if (!iscontinue) return lis.ToArray();
foreach (System.Windows.Forms.Control contr2 in contr.Controls)
{
bool istarget2 = false;
bool iscontinue2 = checktargetcontrol(contr2, ref istarget);
if (istarget2) lis.Add(contr2);
if (!iscontinue2) return lis.ToArray();
}
}
return lis.ToArray();
}
}
8、字符串数目及定位某元素:
/// <summary>
/// 字符串中包含指定字符串的数目
/// </summary>
/// <param name="strSource"></param>
/// <param name="strDe">指定字符串</param>
/// <returns></returns>
public static int StringContainCount(this string strSource, string strDe) {
int result = 0;
if (string.IsNullOrEmpty(strSource) || string.IsNullOrEmpty(strDe) || strSource.Length < strDe.Length) {return result;
}
string str = strSource;
str = str.Replace(strDe, "");
int count = (strSource.Length - str.Length);
if (count > 0) {
result = count / strDe.Length;
}
else {
result = 0;
}
return result;
}
/// <summary>
/// 判断集合字符串是否包含某元素
/// </summary>
/// <param name="strSource">集合字符串</param>
/// <param name="strSplit">分隔符号</param>
/// <param name="strElement">元素字符串</param>
/// <returns></returns>
public static bool ContainElement(this string strSource, string strSplit, string strElement) {
if (string.IsNullOrEmpty(strSource) || string.IsNullOrEmpty(strElement) || strElement.Length > strSource.Length) {
return false;
}
return strSource.Split(new string[] { strSplit }, StringSplitOptions.RemoveEmptyEntries).Contains(strElement);
}