• SiteFactory 通用程序集中(PowerEasy.Common)的常用字符串处理函数



       以下是常用字符处理类StringHelper的各方法,这里给方法添加了简单的注释
    ---------------------
     

           /// <summary>
           /// 使用逗号分割符,扩充字符串
           /// </summary>
           /// <param name="sb"></param>
           /// <param name="append"></param>
            public static void AppendString(StringBuilder sb, string append)
            {
                AppendString(sb, append, ",");
            }
           /// <summary>
            /// 使用分割符,扩充字符串
           /// </summary>
           /// <param name="sb"></param>
           /// <param name="append"></param>
           /// <param name="split"></param>
            public static void AppendString(StringBuilder sb, string append, string split)
            {
                if (sb.Length == 0)
                {
                    sb.Append(append);
                }
                else
                {
                    sb.Append(split);
                    sb.Append(append);
                }
            }
           /// <summary>
           /// 从Base64字符串中还原字符串
           /// </summary>
           /// <param name="input"></param>
           /// <returns></returns>
            public static string Base64StringDecode(string input)
            {
                byte[] bytes = Convert.FromBase64String(input);
                return Encoding.UTF8.GetString(bytes);
            }
           /// <summary>
            /// 将字符串保存为Base64编码序列
           /// </summary>
           /// <param name="input"></param>
           /// <returns></returns>
            public static string Base64StringEncode(string input)
            {
                return Convert.ToBase64String(Encoding.UTF8.GetBytes(input));
            }


           /// <summary>
           /// 将使用long表示的Ip转换为字符串表示
           /// </summary>
           /// <param name="ip"></param>
           /// <returns></returns>
            public static string DecodeIP(long ip)
            {
                string[] strArray = new string[] { ((ip >> 0x18) & 0xffL).ToString(), ".", ((ip >> 0x10) & 0xffL).ToString(), ".", ((ip >> 8) & 0xffL).ToString(), ".", (ip & 0xffL).ToString() };
                return string.Concat(strArray);
            }


            /// <summary>
            /// 将使用字符串表示的IP转换为使用数字值
            /// </summary>
            /// <param name="sip"></param>
            /// <returns></returns>
            public static double EncodeIP(string sip)
            {
                if (string.IsNullOrEmpty(sip))
                {
                    return 0.0;
                }
                string[] strArray = sip.Split(new char[] { '.' });
                long num = 0L;
                foreach (string str in strArray)
                {
                    byte num2;
                    if (byte.TryParse(str, out num2))
                    {
                        num = (num << 8) | num2;
                    }
                    else
                    {
                        return 0.0;
                    }
                }
                return num;
            }

           /// <summary>
           /// 过滤标签,正则匹配时使用非贪婪模式
           /// </summary>
           /// <param name="conStr">待处理的文本数据</param>
           /// <param name="tagName">标签名称如,html,Script等</param>
           /// <param name="fType">过滤方式,可以取(1|2|3)
           /// 1:是单个标签如img等,
           /// 2:表示配对出现的标签如div等将清除此标签已经标签内的全部文本,
           /// 3:表示也是针对配对出现的标签,但是保留标签内的内容.
           /// </param>
           /// <returns></returns>
           public static string CollectionFilter(string conStr, string tagName, int fType)
           {
               string input = conStr;
               switch (fType)
               {
                   case 1:
                       return Regex.Replace(input, "<" + tagName + "([^>])*>", "", RegexOptions.IgnoreCase);

                   case 2:
                       return Regex.Replace(input, "<" + tagName + "([^>])*>.*?</" + tagName + "([^>])*>", "", RegexOptions.IgnoreCase);

                   case 3:
                       return Regex.Replace(Regex.Replace(input, "<" + tagName + "([^>])*>", "", RegexOptions.IgnoreCase), "</" + tagName + "([^>])*>", "", RegexOptions.IgnoreCase);
               }
               return input;
           }
           /// <summary>
           /// 过滤指定的标签
           /// </summary>
           /// <param name="conStr">待过滤文本数据</param>
           /// <param name="filterItem">需要过滤的列表用","阁开如:Iframe,Object,Style,Script,Div</param>
           /// <returns></returns>
            public static string FilterScript(string conStr, string filterItem)
            {
                string str = conStr.Replace("\r", "{$Chr13}").Replace("\n", "{$Chr10}");
                string[] strArray = filterItem.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                foreach (string str2 in strArray)
                {
                    switch (str2)
                    {
                        case "Iframe":
                            str = CollectionFilter(str, str2, 2);
                            break;

                        case "Object":
                            str = CollectionFilter(str, str2, 2);
                            break;

                        case "Script":
                            str = CollectionFilter(str, str2, 2);
                            break;

                        case "Style":
                            str = CollectionFilter(str, str2, 2);
                            break;

                        case "Div":
                            str = CollectionFilter(str, str2, 3);
                            break;

                        case "Span":
                            str = CollectionFilter(str, str2, 3);
                            break;

                        case "Table":
                            str = CollectionFilter(CollectionFilter(CollectionFilter(CollectionFilter(CollectionFilter(str, str2, 3), "Tbody", 3), "Tr", 3), "Td", 3), "Th", 3);
                            break;

                        case "Img":
                            str = CollectionFilter(str, str2, 1);
                            break;

                        case "Font":
                            str = CollectionFilter(str, str2, 3);
                            break;

                        case "A":
                            str = CollectionFilter(str, str2, 3);
                            break;

                        case "Html":
                            str = StripTags(str);
                            goto Label_0218;
                    }
                }
            Label_0218:
                return str.Replace("{$Chr13}", "\r").Replace("{$Chr10}", "\n");
            }

            public static bool FoundCharInArr(string checkStr, string findStr)
            {
                return FoundCharInArr(checkStr, findStr, ",");
            }

            public static bool FoundCharInArr(string checkStr, string findStr, string split)
            {
                bool flag = false;
                if (string.IsNullOrEmpty(split))
                {
                    split = ",";
                }
                if (string.IsNullOrEmpty(checkStr))
                {
                    return false;
                }
                if (checkStr.IndexOf(split) != -1)
                {
                    string[] strArray;
                    if (findStr.IndexOf(split) != -1)
                    {
                        strArray = checkStr.Split(new char[] { Convert.ToChar(split) });
                        string[] strArray2 = findStr.Split(new char[] { Convert.ToChar(split) });
                        foreach (string str in strArray)
                        {
                            foreach (string str2 in strArray2)
                            {
                                if (string.Compare(str, str2) == 0)
                                {
                                    flag = true;
                                    break;
                                }
                            }
                            if (flag)
                            {
                                return flag;
                            }
                        }
                        return flag;
                    }
                    strArray = checkStr.Split(new char[] { Convert.ToChar(split) });
                    foreach (string str in strArray)
                    {
                        if (string.Compare(str, findStr) == 0)
                        {
                            return true;
                        }
                    }
                    return flag;
                }
                if (string.Compare(checkStr, findStr) == 0)
                {
                    flag = true;
                }
                return flag;
            }
           /// <summary>
           /// 在字符串序列中(使用分割符连接的)查找指定值
           /// </summary>
           /// <param name="checkStr"></param>
           /// <param name="findStr"></param>
           /// <param name="split"></param>
           /// <returns></returns>
            public static bool FoundInArr(string checkStr, string findStr, string split)
            {
                bool flag = false;
                if (checkStr.IndexOf(findStr) != -1)
                {
                    string[] strArray = checkStr.Split(new string[] { split }, StringSplitOptions.RemoveEmptyEntries);
                    foreach (string str in strArray)
                    {
                        if (string.Compare(str, findStr) == 0)
                        {
                            return true;
                        }
                    }
                    return flag;
                }
                if (string.Compare(checkStr, findStr) == 0)
                {
                    flag = true;
                }
                return flag;
            }
           /// <summary>
           /// 返回字符串首字符,如果字符串首字符是汉字则返回其拼音的第一个字符(A-Z)
           /// </summary>
           /// <param name="testTxt"></param>
           /// <returns></returns>
            private static string GetGbkX(string testTxt)
            {
                if (testTxt.CompareTo("吖") >= 0)
                {
                    if (testTxt.CompareTo("八") < 0)
                    {
                        return "A";
                    }
                    if (testTxt.CompareTo("嚓") < 0)
                    {
                        return "B";
                    }
                    if (testTxt.CompareTo("咑") < 0)
                    {
                        return "C";
                    }
                    if (testTxt.CompareTo("妸") < 0)
                    {
                        return "D";
                    }
                    if (testTxt.CompareTo("发") < 0)
                    {
                        return "E";
                    }
                    if (testTxt.CompareTo("旮") < 0)
                    {
                        return "F";
                    }
                    if (testTxt.CompareTo("铪") < 0)
                    {
                        return "G";
                    }
                    if (testTxt.CompareTo("讥") < 0)
                    {
                        return "H";
                    }
                    if (testTxt.CompareTo("咔") < 0)
                    {
                        return "J";
                    }
                    if (testTxt.CompareTo("垃") < 0)
                    {
                        return "K";
                    }
                    if (testTxt.CompareTo("嘸") < 0)
                    {
                        return "L";
                    }
                    if (testTxt.CompareTo("拏") < 0)
                    {
                        return "M";
                    }
                    if (testTxt.CompareTo("噢") < 0)
                    {
                        return "N";
                    }
                    if (testTxt.CompareTo("妑") < 0)
                    {
                        return "O";
                    }
                    if (testTxt.CompareTo("七") < 0)
                    {
                        return "P";
                    }
                    if (testTxt.CompareTo("亽") < 0)
                    {
                        return "Q";
                    }
                    if (testTxt.CompareTo("仨") < 0)
                    {
                        return "R";
                    }
                    if (testTxt.CompareTo("他") < 0)
                    {
                        return "S";
                    }
                    if (testTxt.CompareTo("哇") < 0)
                    {
                        return "T";
                    }
                    if (testTxt.CompareTo("夕") < 0)
                    {
                        return "W";
                    }
                    if (testTxt.CompareTo("丫") < 0)
                    {
                        return "X";
                    }
                    if (testTxt.CompareTo("帀") < 0)
                    {
                        return "Y";
                    }
                    if (testTxt.CompareTo("咗") < 0)
                    {
                        return "Z";
                    }
                }
                return testTxt;
            }
           /// <summary>
           /// 返回字串的拼音首字母序列(字串中的英文直接返回)
           /// </summary>
           /// <param name="str"></param>
           /// <returns></returns>
            public static string GetInitial(string str)
            {
                StringBuilder builder = new StringBuilder();
                for (int i = 0; i < str.Length; i++)
                {
                    builder.Append(GetOneIndex(str.Substring(i, 1)));
                }
                return builder.ToString();
            }

            private static string GetOneIndex(string testTxt)
            {
                if ((Convert.ToChar(testTxt) >= '\0') && (Convert.ToChar(testTxt) < 'Ā'))
                {
                    return testTxt;
                }
                return GetGbkX(testTxt);
            }
           /// <summary>
           /// 是否包含中文
           /// </summary>
           /// <param name="inputData"></param>
           /// <returns></returns>
            public static bool IsIncludeChinese(string inputData)
            {
                Regex regex = new Regex("[一-龥]");
                return regex.Match(inputData).Success;
            }
           /// <summary>
           /// 计算MD5散列
           /// </summary>
           /// <param name="input"></param>
           /// <returns></returns>
            public static string MD5(string input)
            {
                using (MD5CryptoServiceProvider provider = new MD5CryptoServiceProvider())
                {
                    return BitConverter.ToString(provider.ComputeHash(Encoding.UTF8.GetBytes(input))).Replace("-", "").ToLower();
                }
            }

            public static int MD5D(string strText)
            {
                using (MD5CryptoServiceProvider provider = new MD5CryptoServiceProvider())
                {
                    byte[] bytes = Encoding.Default.GetBytes(strText);
                    bytes = provider.ComputeHash(bytes);
                    StringBuilder builder = new StringBuilder();
                    foreach (byte num in bytes)
                    {
                        builder.Append(num.ToString("D").ToLower());
                    }
                    string input = builder.ToString();
                    if (input.Length >= 9)
                    {
                        input = "9" + input.Substring(1, 8);
                    }
                    else
                    {
                        input = "9" + input;
                    }
                    provider.Clear();
                    return CLng(input);
                }
            }
           private static int CLng(string input)
           {
               int num;
               int.TryParse(input, out num);
               return num;
           }

           /// <summary>
           /// 使用GB2312编码来计算字符号的MD5值,返回32位序列
           /// </summary>
           /// <param name="input"></param>
           /// <returns></returns>
            public static string MD5gb2312(string input)
            {
                using (MD5CryptoServiceProvider provider = new MD5CryptoServiceProvider())
                {
                    return BitConverter.ToString(provider.ComputeHash(Encoding.GetEncoding("gb2312").GetBytes(input))).Replace("-", "").ToLower();
                }
            }

            public static string RemoveXss(string input)
            {
                string str;
                input = Regex.Replace(input, @"(&#*\w+)[\x00-\x20]+;", "$1;");
                input = Regex.Replace(input, "(&#x*[0-9A-F]+);*", "$1;", RegexOptions.IgnoreCase);
                input = Regex.Replace(input, "&(amp|lt|gt|nbsp|quot);", "&amp;$1;");
                input = HttpUtility.HtmlDecode(input);
                input = Regex.Replace(input, @"[\x00-\x08\x0b-\x0c\x0e-\x19]", "");
                input = Regex.Replace(input, "(<[^>]+[\\x00-\\x20\"'/])(on|xmlns)[^>]*>", "$1>", RegexOptions.IgnoreCase);
                input = Regex.Replace(input, "([a-z]*)[\\x00-\\x20]*=[\\x00-\\x20]*([`'\"]*)[\\x00-\\x20]*j[\\x00-\\x20]*a[\\x00-\\x20]*v[\\x00-\\x20]*a[\\x00-\\x20]*s[\\x00-\\x20]*c[\\x00-\\x20]*r[\\x00-\\x20]*i[\\x00-\\x20]*p[\\x00-\\x20]*t[\\x00-\\x20]*:", "$1=$2nojavascript...", RegexOptions.IgnoreCase);
                input = Regex.Replace(input, "([a-z]*)[\\x00-\\x20]*=[\\x00-\\x20]*([`'\"]*)[\\x00-\\x20]*v[\\x00-\\x20]*b[\\x00-\\x20]*s[\\x00-\\x20]*c[\\x00-\\x20]*r[\\x00-\\x20]*i[\\x00-\\x20]*p[\\x00-\\x20]*t[\\x00-\\x20]*:", "$1=$2novbscript...", RegexOptions.IgnoreCase);
                input = Regex.Replace(input, "(<[^>]+)style[\\x00-\\x20]*=[\\x00-\\x20]*([`'\"]*).*expression[\\x00-\\x20]*\\([^>]*>", "$1>", RegexOptions.IgnoreCase);
                input = Regex.Replace(input, "(<[^>]+)style[\\x00-\\x20]*=[\\x00-\\x20]*([`'\"]*).*behaviour[\\x00-\\x20]*\\([^>]*>", "$1>", RegexOptions.IgnoreCase);
                input = Regex.Replace(input, "(<[^>]+)style[\\x00-\\x20]*=[\\x00-\\x20]*([`'\"]*).*s[\\x00-\\x20]*c[\\x00-\\x20]*r[\\x00-\\x20]*i[\\x00-\\x20]*p[\\x00-\\x20]*t[\\x00-\\x20]*:*[^>]*>", "$1>", RegexOptions.IgnoreCase);
                input = Regex.Replace(input, @"</*\w+:\w[^>]*>", "");
                do
                {
                    str = input;
                    input = Regex.Replace(input, "</*(applet|meta|xml|blink|link|style|script|embed|object|iframe|frame|frameset|ilayer|layer|bgsound|title|base)[^>]*>", "", RegexOptions.IgnoreCase);
                }
                while (str != input);
                return input;
            }
            /// <summary>
            /// 不区分大小写来替换字符串
            /// </summary>
            /// <param name="input"></param>
            /// <param name="oldValue"></param>
            /// <param name="newValue"></param>
            /// <returns></returns>
            public static string ReplaceIgnoreCase(string input, string oldValue, string newValue)
            {
                return Strings.Replace(input, oldValue, newValue, 1, -1, CompareMethod.Text);
            }
           /// <summary>
           /// 使用SHA1计算字符串的散列值
           /// </summary>
           /// <param name="input"></param>
           /// <returns></returns>
            public static string SHA1(string input)
            {
                using (SHA1CryptoServiceProvider provider = new SHA1CryptoServiceProvider())
                {
                    return BitConverter.ToString(provider.ComputeHash(Encoding.UTF8.GetBytes(input))).Replace("-", "").ToLower();
                }
            }
           /// <summary>
           /// 过滤使用使用尖括号括起来的标签,不包括全部HTML定义如(&nbsp;等实体)
           /// </summary>
           /// <param name="input"></param>
           /// <returns></returns>
            public static string StripTags(string input)
            {
                Regex regex = new Regex("<([^<]|\n)+?>");
                return regex.Replace(input, "");
            }
           /// <summary>
           /// 按汉字计2,其他字符计1来取指定长度字符号串
           /// </summary>
           /// <param name="demand">需要截断的字符串</param>
           /// <param name="length">需要的长度</param>
           /// <param name="substitute">省略后替代的字符如:"..."等</param>
           /// <returns></returns>
            public static string SubString(string demand, int length, string substitute)
            {
                if (Encoding.Default.GetBytes(demand).Length <= length)
                {
                    return demand;
                }
                ASCIIEncoding encoding = new ASCIIEncoding();
                length -= Encoding.Default.GetBytes(substitute).Length;
                int num = 0;
                StringBuilder builder = new StringBuilder();
                byte[] bytes = encoding.GetBytes(demand);
                for (int i = 0; i < bytes.Length; i++)
                {
                    if (bytes[i] == 0x3f)
                    {
                        num += 2;
                    }
                    else
                    {
                        num++;
                    }
                    if (num > length)
                    {
                        break;
                    }
                    builder.Append(demand.Substring(i, 1));
                }
                builder.Append(substitute);
                return builder.ToString();
            }
           /// <summary>
           /// 返回字串长度,中文字符为计2,其他计1
           /// 使用ASCII将字符串转化为字节数组时(byte[]),数组长度跟字符串长度相同
           /// 非中文字符取其ASCII码,中文ASCII码为63即?(十六进制为0x3F)
           /// </summary>
           /// <param name="strValue"></param>
           /// <returns></returns>
            public static int StringLength(string strValue)
            {
                if (string.IsNullOrEmpty(strValue))
                {
                    return 0;
                }
                int num = 0;
                byte[] bytes = Encoding.ASCII.GetBytes(strValue);
                for (int i = 0; i < bytes.Length; i++)
                {
                    if (bytes[i] == 0x3f)
                    {
                        num += 2;
                    }
                    else
                    {
                        num++;
                    }
                }
                return num;
            }
           /// <summary>
           /// 去除字串两边的空格,当字串为Null Or Empty时,返回 String.Empty
           /// </summary>
           /// <param name="returnStr"></param>
           /// <returns></returns>
            public static string Trim(string returnStr)
            {
                if (!string.IsNullOrEmpty(returnStr))
                {
                    return returnStr.Trim();
                }
                return string.Empty;
            }
            /// <summary>
            /// 将传入的password参数与md5Value参数进行比较(分别截取md5Valude的16位与32位)
            /// </summary>
            /// <param name="password">MD5后的哈希值</param>
            /// <param name="md5Value">MD5后的哈希值</param>
            /// <returns></returns>
            public static bool ValidateMD5(string password, string md5Value)
            {
                return ((string.Compare(password, md5Value) == 0) || (string.Compare(password, md5Value.Substring(8, 0x10)) == 0));
            }

  • 相关阅读:
    SharePoint学习资料收集
    VS2008 IDE界面
    罗列没有主键的表
    Google Calendar API练习
    pb中数据窗口中字段只显示255个的解决方法
    oracle 中的事务和update from 语句
    sqlserver2005数据库扩容方案
    在一个表上创建非聚集索引和聚集索引
    <xsl:applytemplates/>的应用
    时间戳转换为日期类型
  • 原文地址:https://www.cnblogs.com/wdfrog/p/1219289.html
Copyright © 2020-2023  润新知