字符串处理类

来源:互联网 发布:js防水涂料配多厚 编辑:程序博客网 时间:2024/06/07 05:00

2011年的第一篇,有日子没写了,忙啊。顺便把一个字符串操作类奉上,供大家参考。

 

/// <summary>
/// 字符串的处理
/// </summary>
public class StringUtil
{
    public StringUtil()
    {
        //
        // TODO: 在此处添加构造函数逻辑
        //
    }

    /// <summary>
            /// 将 Stream 转化成 string
            /// </summary>
            /// <param name="s">Stream流</param>
            /// <returns>string</returns>
    public static string ConvertStreamToString(Stream s)
    {
        string strResult    = "";
        StreamReader sr        = new StreamReader( s, Encoding.UTF8 );

        Char[] read = new Char[256];

        // Read 256 charcters at a time.   
        int count = sr.Read( read, 0, 256 );

        while (count > 0)
        {
            // Dump the 256 characters on a string and display the string onto the console.
            string str = new String(read, 0, count);
            strResult += str;
            count = sr.Read(read, 0, 256);
        }


        // 释放资源
        sr.Close();

        return strResult;
    }

    /// <summary>
    /// 对传递的参数字符串进行处理,防止注入式攻击
    /// </summary>
    /// <param name="str">传递的参数字符串</param>
    /// <returns>String</returns>
    public static string ConvertSql(string str)
    {
        str = str.Trim();
        str = str.Replace("'", "''");
        str = str.Replace(";--", "");
        str = str.Replace("=", "");
        str = str.Replace(" or ", "");
        str = str.Replace(" and ", "");

        return str;
    }

    /// <summary>
    /// 格式化占用空间大小的输出
    /// </summary>
    /// <param name="size">大小</param>
    /// <returns>返回 String</returns>
    public static string FormatNUM(long size)
    {
        decimal NUM;
        string strResult;

        if( size > 1073741824 )
        {
            NUM = (Convert.ToDecimal(size)/Convert.ToDecimal(1073741824));
            strResult = NUM.ToString("N") + " M";
        }
        else if( size > 1048576 )
        {
            NUM = (Convert.ToDecimal(size)/Convert.ToDecimal(1048576));
            strResult = NUM.ToString("N") + " M";
        }
        else if( size > 1024 )
        {
            NUM = (Convert.ToDecimal(size)/Convert.ToDecimal(1024));
            strResult = NUM.ToString("N") + " KB";
        }
        else
        {
            strResult = size + " 字节";
        }

        return strResult;
    }

    /// <summary>
    /// 判断字符串是否为有效的邮件地址
    /// </summary>
    /// <param name="email"></param>
    /// <returns></returns>
    public static bool IsValidEmail(string email)
    {
        return Regex.IsMatch(email,@"^.+@([?)[a-zA-Z0-9-.]+.([a-zA-Z]{2,3}|[0-9]{1,3})(]?)$");
    }

    /// <summary>
    /// 判断字符串是否为有效的URL地址
    /// </summary>
    /// <param name="url"></param>
    /// <returns></returns>
    public static bool IsValidURL(string url)
    {
        return Regex.IsMatch(url,@"^(http|https|ftp)://[a-zA-Z0-9-.]+.[a-zA-Z]{2,3}(:[a-zA-Z0-9]*)?/?([a-zA-Z0-9-._?,'//+&%$#=~])*[^.,)(s]$");
    }

    /// <summary>
    /// 判断字符串是否为Int类型的
    /// </summary>
    /// <param name="val"></param>
    /// <returns></returns>
    public static bool IsValidInt(string val)
    {
        return Regex.IsMatch(val,@"^[1-9]d*.?[0]*$");
    }

    /// <summary>
    /// 检测字符串是否全为正整数
    /// </summary>
    /// <param name="str"></param>
    /// <returns></returns>
    public static bool IsNum(string str)
    {
        bool blResult = true;//默认状态下是数字

        if(str == "")
            blResult = false;
        else
        {
            foreach(char Char in str)
            {
                if(!char.IsNumber(Char))
                {
                    blResult = false;
                    break;
                }
            }
            if(blResult)
            {
                if(int.Parse(str) == 0)
                    blResult = false;
            }
        }
        return blResult;
    }

    /// <summary>
    /// 检测字符串是否全为数字型
    /// </summary>
    /// <param name="str"></param>
    /// <returns></returns>
    public static bool IsDouble(string str)
    {
        bool blResult = true;//默认状态下是数字

        if(str == "")
            blResult = false;
        else
        {
            foreach(char Char in str)
            {
                if(!char.IsNumber(Char) && Char.ToString() != "-")
                {
                    blResult = false;
                    break;
                }
            }
        }
        return blResult;
    }

    /// <summary>
    /// 输出由同一字符组成的指定长度的字符串
    /// </summary>
    /// <param name="Char">输出字符,如:A</param>
    /// <param name="i">指定长度</param>
    /// <returns></returns>
    public static string Strings(char Char, int i)
    {
        string strResult = null;

        for(int j = 0; j < i; j++)
        {
            strResult += Char;
        }
        return strResult;
    }

    /// <summary>
    /// 返回字符串的真实长度,一个汉字字符相当于两个单位长度
    /// </summary>
    /// <param name="str">指定字符串</param>
    /// <returns></returns>
    public static int Len(string str)
    {
        int intResult = 0;

        foreach(char Char in str)
        {
            if((int)Char > 127)
                intResult += 2;
            else
                intResult ++;
        }
        return intResult;
    }

    /// <summary>
    /// 以日期为标准获得一个绝对的名称
    /// </summary>
    /// <returns>返回 String</returns>
    public static string MakeName()
    {
        /*
        string y = DateTime.Now.Year.ToString();
        string m = DateTime.Now.Month.ToString();
        string d = DateTime.Now.Day.ToString();
        string h = DateTime.Now.Hour.ToString();
        string n = DateTime.Now.Minute.ToString();
        string s = DateTime.Now.Second.ToString();
        return y + m + d + h + n + s;
        */

        return DateTime.Now.ToString("yyMMddHHmmss");
    }

    /// <summary>
    /// 返回字符串的真实长度,一个汉字字符相当于两个单位长度(使用Encoding类)
    /// </summary>
    /// <param name="str">指定字符串</param>
    /// <returns></returns>
    public static int GetFactualLength(string str)
    {
        int intResult = 0;
        Encoding gb2312 = Encoding.GetEncoding("gb2312");
        byte[] bytes = gb2312.GetBytes(str);
        intResult = bytes.Length;
        return intResult;
    }

    /// <summary>
    /// 按照字符串的实际长度截取指定长度的字符串
    /// </summary>
    /// <param name="str">字符串</param>
    /// <param name="Length">指定长度</param>
    /// <returns></returns>
    public static string TruncateFactualLen(string str, int Length)
    {
        int i = 0, j = 0;
        foreach(char Char in str)
        {
            if((int)Char > 127)
                i += 2;
            else
                i ++;
            if(i > Length)
            {
                str = str.Substring(0, j - 2) + "...";
                break;
            }
            j ++;
        }
        return str;
    }

    /// <summary>
    /// 获取指定长度的纯数字随机数字串
    /// </summary>
    /// <param name="intLong">数字串长度</param>
    /// <returns>字符串</returns>
    public static string RandomNUM(int intLong)
    {
        string strResult = "";

        Random r = new Random();
        for(int i = 0; i < intLong; i ++)
        {
            strResult = strResult + r.Next(10);
        }
        return strResult;
    }

    /// <summary>
    /// 获取一个由26个小写字母组成的指定长度的随即字符串
    /// </summary>
    /// <param name="intLong">指定长度</param>
    /// <returns></returns>
    public static string RandomSTR(int intLong)
    {
        string strResult = "";
        string[] array = {"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"};

        Random r = new Random();

        for(int i = 0; i < intLong; i++)
        {
            strResult += array[r.Next(26)];
        }

        return strResult;
    }

    /// <summary>
    /// 获取一个由数字和26个小写字母组成的指定长度的随即字符串
    /// </summary>
    /// <param name="intLong">指定长度</param>
    /// <returns></returns>
    public static string RandomNUMSTR(int intLong)
    {
        string strResult = "";
        string[] array = {"0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"};

        Random r = new Random();

        for(int i = 0; i < intLong; i++)
        {
            strResult += array[r.Next(36)];
        }

        return strResult;
    }

    /// <summary>
    /// 将简体中文转化成繁体中文
    /// </summary>
    /// <param name="str">简体中文字符串</param>
    /// <returns>string</returns>
    public static string ConvertToTraditionalChinese(string str)
    {
        return Microsoft.VisualBasic.Strings.StrConv(str, VbStrConv.TraditionalChinese, System.Globalization.CultureInfo.CurrentUICulture.LCID);
    }

    /// <summary>
    /// 将繁体中文转化成简体中文
    /// </summary>
    /// <param name="str">繁体中文字符串</param>
    /// <returns>string</returns>
    public static string ConvertToSimplifiedChinese(string str)
    {
        return Microsoft.VisualBasic.Strings.StrConv(str, VbStrConv.SimplifiedChinese, System.Globalization.CultureInfo.CurrentUICulture.LCID);
    }

    /// <summary>
    /// 将指定字符串中的汉字转换为拼音首字母的缩写,其中非汉字保留为原字符
    /// </summary>
    /// <param name="text"></param>
    /// <returns></returns>
    public static string ConvertSpellFirst(string text)
    {
        char pinyin;
        byte[] array;
        StringBuilder sb = new StringBuilder(text.Length);
        foreach(char c in text)
        {
            pinyin = c;
            array = Encoding.Default.GetBytes(new char[]{c});

            if(array.Length == 2)
            {
                int i = array[0] * 0x100 + array[1];

                if(i < 0xB0A1) pinyin = c; else
                    if(i < 0xB0C5) pinyin = 'a'; else
                    if(i < 0xB2C1) pinyin = 'b'; else
                    if(i < 0xB4EE) pinyin = 'c'; else
                    if(i < 0xB6EA) pinyin = 'd'; else
                    if(i < 0xB7A2) pinyin = 'e'; else
                    if(i < 0xB8C1) pinyin = 'f'; else
                    if(i < 0xB9FE) pinyin = 'g'; else
                    if(i < 0xBBF7) pinyin = 'h'; else
                    if(i < 0xBFA6) pinyin = 'g'; else
                    if(i < 0xC0AC) pinyin = 'k'; else
                    if(i < 0xC2E8) pinyin = 'l'; else
                    if(i < 0xC4C3) pinyin = 'm'; else
                    if(i < 0xC5B6) pinyin = 'n'; else
                    if(i < 0xC5BE) pinyin = 'o'; else
                    if(i < 0xC6DA) pinyin = 'p'; else
                    if(i < 0xC8BB) pinyin = 'q'; else
                    if(i < 0xC8F6) pinyin = 'r'; else
                    if(i < 0xCBFA) pinyin = 's'; else
                    if(i < 0xCDDA) pinyin = 't'; else
                    if(i < 0xCEF4) pinyin = 'w'; else
                    if(i < 0xD1B9) pinyin = 'x'; else
                    if(i < 0xD4D1) pinyin = 'y'; else
                    if(i < 0xD7FA) pinyin = 'z';
            }

            sb.Append(pinyin);
        }

        return sb.ToString();
    }

    /// <summary>
    /// 从字符串中的尾部删除指定的字符串
    /// </summary>
    /// <param name="sourceString"></param>
    /// <param name="removedString"></param>
    /// <returns></returns>
    public static string Remove(string sourceString, string removedString)
    {
        try
        {
            if (sourceString.IndexOf(removedString) < 0)
                throw new Exception("原字符串中不包含移除字符串!");
            string result = sourceString;
            int lengthOfSourceString = sourceString.Length;
            int lengthOfRemovedString = removedString.Length;
            int startIndex = lengthOfSourceString - lengthOfRemovedString;
            string tempSubString = sourceString.Substring(startIndex);
            if (tempSubString.ToUpper() == removedString.ToUpper())
            {
                result = sourceString.Remove(startIndex, lengthOfRemovedString);
            }
            return result;
        }
        catch
        {
            return sourceString;
        }
    }

    /// <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;
    }

    /// <summary>
    /// 去掉最后一个逗号
    /// </summary>
    /// <param name="origin"></param>
    /// <returns></returns>
    public static string DelLastComma(string origin)
    {
        if (origin.IndexOf(",") == -1)
        {
            return origin;
        }
        return origin.Substring(0, origin.LastIndexOf(","));
    }

    /// <summary>
    /// 删除不可见字符
    /// </summary>
    /// <param name="sourceString"></param>
    /// <returns></returns>
    public static string DeleteUnVisibleChar(string sourceString)
    {
        System.Text.StringBuilder sBuilder = new System.Text.StringBuilder(131);
        for (int i = 0; i < sourceString.Length; i++)
        {
            int Unicode = sourceString[i];
            if (Unicode >= 16)
            {
                sBuilder.Append(sourceString[i].ToString());
            }
        }
        return sBuilder.ToString();
    }

    /// <summary>
    /// 获取数组元素的合并字符串
    /// </summary>
    /// <param name="stringArray"></param>
    /// <returns></returns>
    public static string GetArrayString(string[] stringArray)
    {
        string totalString = null;
        for (int i = 0; i < stringArray.Length; i++)
        {
            totalString = totalString + stringArray[i];
        }
        return totalString;
    }

    /// <summary>
    ///     获取某一字符串在字符串数组中出现的次数
    /// </summary>
    /// <param name="stringArray" type="string[]">
    ///     <para>
    ///         
    ///     </para>
    /// </param>
    /// <param name="findString" type="string">
    ///     <para>
    ///         
    ///     </para>
    /// </param>
    /// <returns>
    ///     A int value...
    /// </returns>
    public static int GetStringCount(string[] stringArray, string findString)
    {
        int count = -1;
        string totalString = GetArrayString(stringArray);
        string subString = totalString;

        while (subString.IndexOf(findString) >= 0)
        {
            subString = totalString.Substring(subString.IndexOf(findString));
            count += 1;
        }
        return count;
    }

    /// <summary>
    ///     获取某一字符串在字符串中出现的次数
    /// </summary>
    /// <param name="stringArray" type="string">
    ///     <para>
    ///         原字符串
    ///     </para>
    /// </param>
    /// <param name="findString" type="string">
    ///     <para>
    ///         匹配字符串
    ///     </para>
    /// </param>
    /// <returns>
    ///     匹配字符串数量
    /// </returns>
    public static int GetStringCount(string sourceString, string findString)
    {
        int count = 0;
        int findStringLength = findString.Length;
        string subString = sourceString;

        while (subString.IndexOf(findString) >= 0)
        {
            subString = subString.Substring(subString.IndexOf(findString) + findStringLength);
            count += 1;
        }
        return count;
    }

    /// <summary>
    /// 截取从startString开始到原字符串结尾的所有字符   
    /// </summary>
    /// <param name="sourceString" type="string">
    ///     <para>
    ///         
    ///     </para>
    /// </param>
    /// <param name="startString" type="string">
    ///     <para>
    ///         
    ///     </para>
    /// </param>
    /// <returns>
    ///     A string value...
    /// </returns>
    public static string GetSubString(string sourceString, string startString)
    {
        try
        {
            int index = sourceString.ToUpper().IndexOf(startString);
            if (index > 0)
            {
                return sourceString.Substring(index);
            }
            return sourceString;
        }
        catch
        {
            return "";
        }
    }

    public static string GetSubString(string sourceString, string beginRemovedString, string endRemovedString)
    {
        try
        {
            if (sourceString.IndexOf(beginRemovedString) != 0)
                beginRemovedString = "";

            if (sourceString.LastIndexOf(endRemovedString, sourceString.Length - endRemovedString.Length) < 0)
                endRemovedString = "";

            int startIndex = beginRemovedString.Length;
            int length = sourceString.Length - beginRemovedString.Length - endRemovedString.Length;
            if (length > 0)
            {
                return sourceString.Substring(startIndex, length);
            }
            return sourceString;
        }
        catch
        {
            return sourceString; ;
        }
    }

    /// <summary>
    /// 按字节数取出字符串的长度
    /// </summary>
    /// <param name="strTmp">要计算的字符串</param>
    /// <returns>字符串的字节数</returns>
    public static int GetByteCount(string strTmp)
    {
        int intCharCount = 0;
        for (int i = 0; i < strTmp.Length; i++)
        {
            if (System.Text.UTF8Encoding.UTF8.GetByteCount(strTmp.Substring(i, 1)) == 3)
            {
                intCharCount = intCharCount + 2;
            }
            else
            {
                intCharCount = intCharCount + 1;
            }
        }
        return intCharCount;
    }

    /// <summary>
    /// 按字节数要在字符串的位置
    /// </summary>
    /// <param name="intIns">字符串的位置</param>
    /// <param name="strTmp">要计算的字符串</param>
    /// <returns>字节的位置</returns>
    public static int GetByteIndex(int intIns, string strTmp)
    {
        int intReIns = 0;
        if (strTmp.Trim() == "")
        {
            return intIns;
        }
        for (int i = 0; i < strTmp.Length; i++)
        {
            if (System.Text.UTF8Encoding.UTF8.GetByteCount(strTmp.Substring(i, 1)) == 3)
            {
                intReIns = intReIns + 2;
            }
            else
            {
                intReIns = intReIns + 1;
            }
            if (intReIns >= intIns)
            {
                intReIns = i + 1;
                break;
            }
        }
        return intReIns;
    }

    /// <summary>
    /// Method to make sure that user's inputs are not malicious
    /// 截取输入最大的字符串
    /// </summary>
    /// <param name="text">User's Input</param>
    /// <param name="maxLength">Maximum length of input</param>
    /// <returns>The cleaned up version of the input</returns>
    public static string InputText(string text, int maxLength)
    {
        text = text.Trim();
        if (string.IsNullOrEmpty(text))
            return string.Empty;
        if (text.Length > maxLength)
            text = text.Substring(0, maxLength);
        text = Regex.Replace(text, "[//s]{2,}", " ");   //two or more spaces
        text = Regex.Replace(text, "(<[b|B][r|R]/*>)+|(<[p|P](.|//n)*?>)", "/n");   //<br>
        text = Regex.Replace(text, "(//s*&[n|N][b|B][s|S][p|P];//s*)+", " ");   // 
        text = Regex.Replace(text, "<(.|//n)*?>", string.Empty);    //any other tags
        text = text.Replace("'", "''");
        return text;
    }

    /// <summary>
    /// Method to check whether input has other characters than numbers
    /// 清楚字符
    /// </summary>
    public static string CleanNonWord(string text)
    {
        return Regex.Replace(text, "//W", "");
    }

    //特殊字符的转换
    public static string Encode(string str)
    {

        str = str.Replace("'", "'");
        str = str.Replace("/"", """);
        str = str.Replace("<", "<");
        str = str.Replace(">", ">");
        return str;
    }
    public static string Decode(string str)
    {

        str = str.Replace(">", ">");
        str = str.Replace("<", "<");
        str = str.Replace(" ", " ");
        str = str.Replace(""", "/"");
        return str;
    }
    //字符传的转换 用在查询 登陆时 防止恶意的盗取密码
    public static string TBCode(string strtb)
    {
        strtb = strtb.Replace("!", "");
        strtb = strtb.Replace("@", "");
        strtb = strtb.Replace("#", "");
        strtb = strtb.Replace("$", "");
        strtb = strtb.Replace("%", "");
        strtb = strtb.Replace("^", "");
        strtb = strtb.Replace("&", "");
        strtb = strtb.Replace("*", "");
        strtb = strtb.Replace("(", "");
        strtb = strtb.Replace(")", "");
        strtb = strtb.Replace("_", "");
        strtb = strtb.Replace("+", "");
        strtb = strtb.Replace("|", "");
        strtb = strtb.Replace("?", "");
        strtb = strtb.Replace("/", "");
        strtb = strtb.Replace(".", "");
        strtb = strtb.Replace(">", "");
        strtb = strtb.Replace("<", "");
        strtb = strtb.Replace("{", "");
        strtb = strtb.Replace("}", "");
        strtb = strtb.Replace("[", "");
        strtb = strtb.Replace("]", "");
        strtb = strtb.Replace("-", "");
        strtb = strtb.Replace("=", "");
        strtb = strtb.Replace(",", "");
        return strtb;
    }

    //以javascript的windous.alert()方法输出提示信息
    //strmsg 表示要输出的信息
    //back 表示输出后是否要history.back()
    //end 表示输出后是否要Response.End()
    public static void WriteMessage(string strMsg, bool Back, bool End)
    {
        string js = "";
       // Response = HttpContext.Current.Response;
        //将单引号替换,防止js出错
        strMsg = strMsg.Replace("'", "");
        //将回车符号换掉,防止js出错
        strMsg = strMsg.Replace("/r/n", "");
       js="<script language=javascript>alert('" + strMsg + "')</script>";
        if (Back)
        {
            js="<script language=javascript>history.back();</script)";
        }
        if (End)
        {
            js = "<script language=javascript>End</script)";
        }
        HttpContext.Current.Response.Write(js);   
    }

    /// <summary>
    /// 小函数,将字符串转换成float型,若字符串为空,返回0
    /// </summary>
    /// <param name="str">要转换的字符串</param>
    /// <returns>转后的float值</returns>
    public static float GetFloatValue(string str)
    {
        try
        {
            if (str.Length == 0)
                return 0;
            else
                return float.Parse(str);
        }
        catch
        {
            WriteMessage("数据转换失败,请检查数据是否合理!", true, true);
            return 0;
        }
    }

    /// <summary>
    /// 小函数,将字符串转换成int型,若字符串为空,返回0
    /// </summary>
    /// <param name="str">要转换的字符串</param>
    /// <returns>转后的int值</returns>
    public static int GetIntValue(string str)
    {
        try
        {
            if (str.Length == 0)
                return 0;
            else
            {
                if (Int32.Parse(str) == 0)
                    return 0;
                else
                    return Int32.Parse(str);
            }
        }
        catch
        {
            WriteMessage("数据转换失败,请检查数据是否合理!", true, true);
            return 0;
        }
    }
}

原创粉丝点击