StringHelper.cs(20170223)
using Microsoft.AspNetCore.Mvc.RazorPages; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; using System.IO.Compression; using System.Web; //using System.Web.UI; namespace WebApplication1 { public class StringHelper { #region 字符与List<string> /// <summary> /// 把字符串按照分隔符转换成 List /// </summary> /// <param name="str">源字符串</param> /// <param name="speater">分隔符</param> /// <param name="toLower">是否转换为小写</param> /// <returns></returns> public static List<string> GetStrArray(string str, char speater, bool toLower) { List<string> list = new List<string>(); string[] ss = str.Split(speater); foreach (string s in ss) { if (!string.IsNullOrEmpty(s) && s != speater.ToString()) { string strVal = s; if (toLower) { strVal = s.ToLower(); } list.Add(strVal); } } return list; } /// <summary> /// 把 List<string> 按照分隔符组装成 string /// </summary> /// <param name="list"></param> /// <param name="speater"></param> /// <returns></returns> //public static string GetArrayStr(List<string> list, string speater) //{ // StringBuilder sb = new StringBuilder(); // for (int i = 0; i < list.Count; i++) // { // if (i == list.Count - 1) // { // sb.Append(list[0][i]); // } // else // { // sb.Append(list[size]); // sb.Append(speater); // } // } // return sb.ToString(); //} /// <summary> /// 把字符串按照指定分隔符装成 List 去除重复 /// </summary> /// <param name="o_str"></param> /// <param name="sepeater"></param> /// <returns></returns> public static List<string> GetSubStringList(string o_str, char sepeater) { List<string> list = new List<string>(); string[] ss = o_str.Split(sepeater); foreach (string s in ss) { if (!string.IsNullOrEmpty(s) && s != sepeater.ToString()) { list.Add(s); } } return list; } #endregion #region 删除字符与截取字符 /// <summary> /// 删除最后结尾的一个逗号 /// </summary> public static string DelLastComma(string str) { return str.Substring(0, str.LastIndexOf(",")); } /// <summary> /// 删除最后结尾的指定字符后的字符 /// </summary> public static string DelLastChar(string str, string strchar) { return str.Substring(0, str.LastIndexOf(strchar)); } #endregion #region 提取文字 /// <summary> /// 提取字符串中的英文 /// </summary> /// <param name="str"></param> /// <returns></returns> public string GetSubString(string str) { string fid = str; Regex re = new Regex(@"[a-zA-Z]+"); Match m = re.Match(fid); return m.Value; } #endregion #region 分割字符 /// <summary> /// 分割字符串 /// </summary> /// <param name="str">要分割的字符</param> /// <param name="splitstr">分割标识符</param> /// <returns></returns> public static string[] SplitMulti(string str, string splitstr) { string[] strArray = null; if ((str != null) && (str != "")) { strArray = new Regex(splitstr).Split(str); } return strArray; } /// <summary> /// 获取拆分符右边的字符串 /// </summary> /// <param name="sourceString"></param> /// <param name="splitChar"></param> /// <returns></returns> public static string RightSplit(string sourceString, char splitChar) { string result = null; string[] tempString = sourceString.Split(splitChar); if (tempString.Length > 0) { result = tempString[tempString.Length - 1].ToString(); } return result; } /// <summary> /// 获取拆分符左边的字符串 /// </summary> /// <param name="sourceString"></param> /// <param name="splitChar"></param> /// <returns></returns> public static string LeftSplit(string sourceString, char splitChar) { string result = null; string[] tempString = sourceString.Split(splitChar); if (tempString.Length > 0) { result = tempString[0].ToString(); } return result; } #endregion #region 字符与数字 /// <summary> /// 获取正确的Id,如果不是正整数,返回0 /// </summary> /// <param name="_value"></param> /// <returns>返回正确的整数ID,失败返回0</returns> public static int StrToId(string _value) { if (IsNumberId(_value)) return int.Parse(_value); else return 0; } /// <summary> /// 检查一个字符串是否是纯数字构成的,一般用于查询字符串参数的有效性验证。(0除外) /// </summary> /// <param name="_value">需验证的字符串。。</param> /// <returns>是否合法的bool值。</returns> public static bool IsNumberId(string _value) { return QuickValidate("^[1-9]*[0-9]*$", _value); } /// <summary> /// 检查一个字符串是否是纯数字 /// </summary> /// <param name="_value">需验证的字符串。。</param> /// <returns>是否合法的bool值。</returns> public static bool IsNaN(string _value) { return QuickValidate("^[0-9]*$", _value); } /// <summary> /// 快速验证一个字符串是否符合指定的正则表达式。 /// </summary> /// <param name="_express">正则表达式的内容。</param> /// <param name="_value">需验证的字符串。</param> /// <returns>是否合法的bool值。</returns> public static bool QuickValidate(string _express, string _value) { if (_value == null) return false; Regex myRegex = new Regex(_express); if (_value.Length == 0) { return false; } return myRegex.IsMatch(_value); } #endregion #region 判断对象是否为空 /// <summary> /// 判断对象是否为空,为空返回true /// </summary> /// <typeparam name="T">要验证的对象的类型</typeparam> /// <param name="data">要验证的对象</param> public static bool IsNullOrEmpty<T>(T data) { //如果为null if (data == null) { return true; } //如果为"" if (data.GetType() == typeof(String)) { if (string.IsNullOrEmpty(data.ToString().Trim())) { return true; } } //如果为DBNull if (data.GetType() == typeof(DBNull)) { return true; } //不为空 return false; } /// <summary> /// 判断对象是否为空,为空返回true /// </summary> /// <param name="data">要验证的对象</param> public static bool IsNullOrEmpty(object data) { //如果为null if (data == null) { return true; } //如果为"" if (data.GetType() == typeof(String)) { if (string.IsNullOrEmpty(data.ToString().Trim())) { return true; } } //如果为DBNull if (data.GetType() == typeof(DBNull)) { return true; } //不为空 return false; } #endregion #region 字符长度 /// <summary> /// 返回字符串真实长度, 1个汉字长度为2 /// </summary> /// <returns></returns> public static int GetStringLength(string str) { return Encoding.Default.GetBytes(str).Length; } #endregion #region 字符与数组 /// <summary> /// 判断指定字符串在指定字符串数组中的位置 /// </summary> /// <param name="strSearch">字符串</param> /// <param name="stringArray">字符串数组</param> /// <param name="caseInsensetive">是否不区分大小写, true为不区分, false为区分</param> /// <returns>字符串在指定字符串数组中的位置, 如不存在则返回-1</returns> public static int GetInArrayID(string strSearch, string[] stringArray, bool caseInsensetive) { for (int i = 0; i < stringArray.Length; i++) { if (caseInsensetive) { if (strSearch.ToLower() == stringArray[i].ToLower()) { return i; } } else { if (strSearch == stringArray[i]) { return i; } } } return -1; } /// <summary> /// 判断指定字符串在指定字符串数组中的位置 /// </summary> /// <param name="strSearch">字符串</param> /// <param name="stringArray">字符串数组</param> /// <returns>字符串在指定字符串数组中的位置, 如不存在则返回-1</returns> public static int GetInArrayID(string strSearch, string[] stringArray) { return GetInArrayID(strSearch, stringArray, true); } #endregion #region 清理字符 /// <summary> /// 删除字符串尾部的回车/换行/空格/制表符 /// </summary> /// <param name="str"></param> /// <returns></returns> public static string RTrim(string str) { for (int i = str.Length; i >= 0; i--) { if (str.Equals(" ") || str.Equals("\r") || str.Equals("\n") || str.Equals("\t")) { str.Remove(i, 1); } } return str; } /// <summary> /// 清理字符串 /// </summary> public static string CleanInput(string strIn) { return Regex.Replace(strIn.Trim(), @"[^\w\.@-]", ""); } #endregion #region 字符与html /// <summary> /// 返回 HTML 字符串的编码结果 /// </summary> /// <param name="str">字符串</param> /// <returns>编码结果</returns> public static string HtmlEncode(string str) { if (str == null) return null; return str.Replace(" ", " ").Replace("\r\n", "<br />"); } /// <summary> /// 返回 HTML 字符串的解码结果 /// </summary> /// <param name="str">字符串</param> /// <returns>解码结果</returns> public static string HtmlDecode(string str) { if (str == null) return null; return str.Replace(" ", " ").Replace("<br />", "\r\n"); } #endregion #region 字符与URL编码 /// <summary> /// 返回 URL 字符串的编码结果 /// </summary> /// <param name="str">字符串</param> /// <returns>编码结果</returns> public static string UrlEncode(string str) { return HttpUtility.UrlEncode(str); } /// <summary> /// 返回 URL 字符串的解码结果 /// </summary> /// <param name="str">字符串</param> /// <returns>解码结果</returns> public static string UrlDecode(string str) { return HttpUtility.UrlDecode(str); } #endregion #region 压缩字符串 /// <summary> /// 压缩字符串 /// </summary> /// <param name="unCompressedString">要压缩的字符串</param> /// <returns></returns> public static string ZipString(string unCompressedString) { byte[] bytData = System.Text.Encoding.UTF8.GetBytes(unCompressedString); MemoryStream ms = new MemoryStream(); Stream s = new GZipStream(ms, CompressionMode.Compress); s.Write(bytData, 0, bytData.Length); s.Close(); byte[] compressedData = (byte[])ms.ToArray(); return System.Convert.ToBase64String(compressedData, 0, compressedData.Length); } /// <summary> /// 解压字符串 /// </summary> /// <param name="unCompressedString">要解压的字符串</param> /// <returns></returns> public static string UnzipString(string unCompressedString) { System.Text.StringBuilder uncompressedString = new System.Text.StringBuilder(); byte[] writeData = new byte[4096]; byte[] bytData = System.Convert.FromBase64String(unCompressedString); int totalLength = 0; int size = 0; Stream s = new GZipStream(new MemoryStream(bytData), CompressionMode.Decompress); while (true) { size = s.Read(writeData, 0, writeData.Length); if (size > 0) { totalLength += size; uncompressedString.Append(System.Text.Encoding.UTF8.GetString(writeData, 0, size)); } else { break; } } s.Close(); return uncompressedString.ToString(); } #endregion #region 字符转换 /// <summary> /// 英文字符转中文字符 /// </summary> /// <param name="input"></param> /// <returns></returns> public static string ToSBC(string input) { //半角转全角: char[] c = input.ToCharArray(); for (int i = 0; i < c.Length; i++) { if (c[i] == 32) { c[i] = (char)12288; continue; } if (c[i] < 127) c[i] = (char)(c[i] + 65248); } return new string(c); } /// <summary> /// 中文字符转英文字符 /// </summary> /// <param name="input"></param> /// <returns></returns> public static string ToDBC(string input) { char[] c = input.ToCharArray(); for (int i = 0; i < c.Length; i++) { if (c[i] == 12288) { c[i] = (char)32; continue; } if (c[i] > 65280 && c[i] < 65375) c[i] = (char)(c[i] - 65248); } return new string(c); } #endregion #region 其他 /// <summary> /// 生成唯一ID /// </summary> /// <returns></returns> public static string CreateIDCode() { DateTime Time1 = DateTime.Now.ToUniversalTime(); DateTime Time2 = Convert.ToDateTime("1970-01-01"); TimeSpan span = Time1 - Time2; //span就是两个日期之间的差额 string t = span.TotalMilliseconds.ToString("0"); return t; } #endregion #region 字符与sql /// <summary> ///SQL注入过滤 /// </summary> /// <param name="InText">要进行过滤的字符串</param> /// <returns>如果参数存在不安全字符,则返回true</returns> public static bool SqlFilter2(string InText) { string word = "exec|insert|select|delete|update|chr|mid|master|or|truncate|char|declare|join"; if (InText == null) return false; foreach (string i in word.Split('|')) { if ((InText.ToLower().IndexOf(i + " ") > -1) || (InText.ToLower().IndexOf(" " + i) > -1)) { return true; } } return false; } /// <summary> /// sql过滤关键字 /// </summary> /// <param name="sWord"></param> /// <returns></returns> public static bool SqlCheckKeyWord(string sWord) { //过滤关键字 string StrKeyWord = @"select|insert|delete|from|count\(|drop table|update|truncate|asc\(|mid\(|char\(|xp_cmdshell|exec master|netlocalgroup administrators|:|net user|""|or|and"; //过滤关键字符 string StrRegex = @"[-|;|,|/|\(|\)|\[|\]|}|{|%|\@|*|!|']"; if (Regex.IsMatch(sWord, StrKeyWord, RegexOptions.IgnoreCase) || Regex.IsMatch(sWord, StrRegex)) return true; return false; } /// <summary> /// 将指定的str串执行sql关键字过滤并返回 /// </summary> /// <param name="str">要过滤的字符串</param> /// <returns></returns> public static string SqlFilter(string str) { return str.Replace("'", "").Replace("'", "").Replace("--", "").Replace("&", "").Replace("/*", "").Replace(";", "").Replace("%", ""); } /// <summary> /// 将指定的串列表执行sql关键字过滤并以[,]号分隔返回 /// </summary> /// <param name="strs"></param> /// <returns></returns> public static string SqlFilters(params string[] strs) { StringBuilder sb = new StringBuilder(); foreach (string str in strs) { sb.Append(SqlFilter(str) + ","); } if (sb.Length > 0) return sb.ToString().TrimEnd(','); return ""; } public static bool ProcessSqlStr(string Str) { bool ReturnValue = false; try { if (Str != "") { string SqlStr = "'|insert|select*|and'|or'|insertinto|deletefrom|altertable|update|createtable|createview|dropview|createindex|dropindex|createprocedure|dropprocedure|createtrigger|droptrigger|createschema|dropschema|createdomain|alterdomain|dropdomain|);|select@|declare@|print@|char(|select"; string[] anySqlStr = SqlStr.Split('|'); foreach (string ss in anySqlStr) { if (Str.IndexOf(ss) >= 0) { ReturnValue = true; } } } } catch { ReturnValue = true; } return ReturnValue; } #endregion #region IP地址 /// <summary> /// 获取客户端ip /// </summary> /// <param name="page"></param> /// <returns></returns> //public static string GetIP(Page page) //{ // string IP = (page.Request.ServerVariables["HTTP_VIA"] != null) ? page.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString() : page.Request.ServerVariables["REMOTE_ADDR"].ToString(); // return IP; //} /// <summary> /// 判断指定ip是否为本公司ip、 /// 是则返回true /// </summary> /// <param name="page"></param> /// <param name="ip"></param> /// <returns></returns> //public static bool IsCompanyIp(Page page) //{ // string ip = (page.Request.ServerVariables["HTTP_VIA"] != null) ? page.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString() : page.Request.ServerVariables["REMOTE_ADDR"].ToString(); // bool b = false; // //公司外网140.206.53.134,公司内网192.168,未发布前本地::1 // if (ip == "140.206.53.134" || ip.Contains("192.168") || ip == "::1") // { // b = true; // } // return b; //} #endregion /// <summary> /// 中文转UTF-8编码 /// </summary> /// <param name="str"></param> /// <returns></returns> public static string ChineseToUTF8(string str) { string s = ""; string strencode = ""; string t = ""; StringBuilder res = new StringBuilder(); //字符串拆解成一个个字符 for (int i = 0; i < str.Length; i++) { s = str.Substring(i, 1); //判断是否为汉字 if (Regex.IsMatch(s, @"^[\u4e00-\u9fa5]+$")) { //全汉字 for (int j = 0; j < 2; j++) { //开始编码转换 t = Encoding.UTF32.GetBytes(s)[j].ToString("X"); if (t.Length == 1) { t = "0" + t; } strencode = strencode.Insert(0, t); } strencode = strencode.Insert(0, "&#x") + ";"; res.Append(strencode); strencode = ""; } else { //非全汉字 res.Append(s); } } return res.ToString(); } } }