博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
StringHelper.cs(20170223)
阅读量:4627 次
发布时间:2019-06-09

本文共 12093 字,大约阅读时间需要 40 分钟。

using System;using System.Collections.Generic;using System.IO;using System.IO.Compression;using System.Linq;using System.Text;using System.Text.RegularExpressions;using System.Threading.Tasks;using System.Web;using System.Web.UI;namespace System.CRM.Common{    public class StringHelper    {        #region 字符与List
///
/// 把字符串按照分隔符转换成 List /// ///
源字符串 ///
分隔符 ///
是否转换为小写 ///
public static List
GetStrArray(string str, char speater, bool toLower) { List
list = new List
(); 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; } ///
/// 把 List
按照分隔符组装成 string ///
///
///
///
//public static string GetArrayStr(List
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(); //} ///
/// 把字符串按照指定分隔符装成 List 去除重复 /// ///
///
///
public static List
GetSubStringList(string o_str, char sepeater) { List
list = new List
(); 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 删除字符与截取字符 ///
/// 删除最后结尾的一个逗号 /// public static string DelLastComma(string str) { return str.Substring(0, str.LastIndexOf(",")); } ///
/// 删除最后结尾的指定字符后的字符 /// public static string DelLastChar(string str, string strchar) { return str.Substring(0, str.LastIndexOf(strchar)); } #endregion #region 分割字符 ///
/// 分割字符串 /// ///
要分割的字符 ///
分割标识符 ///
public static string[] SplitMulti(string str, string splitstr) { string[] strArray = null; if ((str != null) && (str != "")) { strArray = new Regex(splitstr).Split(str); } return strArray; } ///
/// 获取拆分符右边的字符串 /// ///
///
///
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; } ///
/// 获取拆分符左边的字符串 /// ///
///
///
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 字符与数字 ///
/// 获取正确的Id,如果不是正整数,返回0 /// ///
///
返回正确的整数ID,失败返回0
public static int StrToId(string _value) { if (IsNumberId(_value)) return int.Parse(_value); else return 0; } ///
/// 检查一个字符串是否是纯数字构成的,一般用于查询字符串参数的有效性验证。(0除外) /// ///
需验证的字符串。。 ///
是否合法的bool值。
public static bool IsNumberId(string _value) { return QuickValidate("^[1-9]*[0-9]*$", _value); } ///
/// 检查一个字符串是否是纯数字 /// ///
需验证的字符串。。 ///
是否合法的bool值。
public static bool IsNaN(string _value) { return QuickValidate("^[0-9]*$", _value); } ///
/// 快速验证一个字符串是否符合指定的正则表达式。 /// ///
正则表达式的内容。 ///
需验证的字符串。 ///
是否合法的bool值。
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 判断对象是否为空 ///
/// 判断对象是否为空,为空返回true /// ///
要验证的对象的类型
///
要验证的对象 public static bool IsNullOrEmpty
(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; } ///
/// 判断对象是否为空,为空返回true /// ///
要验证的对象 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 字符长度 ///
/// 返回字符串真实长度, 1个汉字长度为2 /// ///
public static int GetStringLength(string str) { return Encoding.Default.GetBytes(str).Length; } #endregion #region 字符与数组 ///
/// 判断指定字符串在指定字符串数组中的位置 /// ///
字符串 ///
字符串数组 ///
是否不区分大小写, true为不区分, false为区分 ///
字符串在指定字符串数组中的位置, 如不存在则返回-1
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; } ///
/// 判断指定字符串在指定字符串数组中的位置 /// ///
字符串 ///
字符串数组 ///
字符串在指定字符串数组中的位置, 如不存在则返回-1
public static int GetInArrayID(string strSearch, string[] stringArray) { return GetInArrayID(strSearch, stringArray, true); } #endregion #region 清理字符 ///
/// 删除字符串尾部的回车/换行/空格/制表符 /// ///
///
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; } ///
/// 清理字符串 /// public static string CleanInput(string strIn) { return Regex.Replace(strIn.Trim(), @"[^\w\.@-]", ""); } #endregion #region 字符与html ///
/// 返回 HTML 字符串的编码结果 /// ///
字符串 ///
编码结果
public static string HtmlEncode(string str) { if (str == null) return null; return str.Replace(" ", " ").Replace("\r\n", "
"); } ///
/// 返回 HTML 字符串的解码结果 /// ///
字符串 ///
解码结果
public static string HtmlDecode(string str) { if (str == null) return null; return str.Replace(" ", " ").Replace("
", "\r\n"); } #endregion #region 字符与URL编码 ///
/// 返回 URL 字符串的编码结果 /// ///
字符串 ///
编码结果
public static string UrlEncode(string str) { return HttpUtility.UrlEncode(str); } ///
/// 返回 URL 字符串的解码结果 /// ///
字符串 ///
解码结果
public static string UrlDecode(string str) { return HttpUtility.UrlDecode(str); } #endregion #region 压缩字符串 ///
/// 压缩字符串 /// ///
要压缩的字符串 ///
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); } ///
/// 解压字符串 /// ///
要解压的字符串 ///
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 字符转换 ///
/// 英文字符转中文字符 /// ///
///
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); } ///
/// 中文字符转英文字符 /// ///
///
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 其他 ///
/// 生成唯一ID /// ///
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 ///
///SQL注入过滤 /// ///
要进行过滤的字符串 ///
如果参数存在不安全字符,则返回true
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; } ///
/// sql过滤关键字 /// ///
///
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; } ///
/// 将指定的str串执行sql关键字过滤并返回 /// ///
要过滤的字符串 ///
public static string SqlFilter(string str) { return str.Replace("'", "").Replace("'", "").Replace("--", "").Replace("&", "").Replace("/*", "").Replace(";", "").Replace("%", ""); } ///
/// 将指定的串列表执行sql关键字过滤并以[,]号分隔返回 /// ///
///
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地址 ///
/// 获取客户端ip /// ///
///
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; } ///
/// 判断指定ip是否为本公司ip、 /// 是则返回true /// ///
///
///
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();
}

}}

 

转载于:https://www.cnblogs.com/zyx321/p/6435933.html

你可能感兴趣的文章
css实现等高布局
查看>>
CH03_06.mxml 一个文本输入框复制到另外一个文本输入框
查看>>
malloc/free和new/delete
查看>>
spoj104 highways 生成树计数(矩阵树定理)
查看>>
nginx配置多个域名
查看>>
ARM寻址方式
查看>>
pandas之时间序列
查看>>
补肾的十大食物是什么?
查看>>
iPhone开发之 - 苹果推送通知服务(APNs)编程
查看>>
ASP常用读取数据2个调用方式
查看>>
【大话UWB定位】之蓝牙定位的烦恼
查看>>
算法3-高级排序
查看>>
每天一个linux命令(17):whereis 命令
查看>>
Angular4+路由
查看>>
Codeforces-234C Weather
查看>>
面向对象编程思想及其相关内容
查看>>
Leetcode解题笔记-3sum
查看>>
Android 3.0 Hardware Acceleration
查看>>
【2011 Greater New York Regional 】Problem G: Rancher's Gift
查看>>
java常见题目总结
查看>>