码迷,mamicode.com
首页 > 其他好文 > 详细

字符串处理增强类

时间:2015-07-06 14:07:41      阅读:121      评论:0      收藏:0      [点我收藏+]

标签:

/// <summary> 
    /// 字符串处理增强类
    /// </summary> 
    public sealed class StringTool
    {
        /// <summary>
        /// 将txt文件读入字符串
        /// </summary>
        /// <param name="aPath"></param>
        /// <returns></returns>
        public static string ReadTextFile(string aPath)
        {
            string text = "";
            using (TextReader tr = new StreamReader(aPath))
            {
                text = tr.ReadToEnd();
            }
            return text;
        }
 
        /// <summary>
        /// 将16进行编码的字符串写入到指定的文件路径
        /// </summary>
        /// <param name="aPath"></param>
        /// <param name="aText"></param>
        public static void WriteTextFile(string aPath, string aText)
        {
            using (TextWriter tw = new StreamWriter(aPath))
            {
                tw.Write(aText);
            }
        }
 
        /// <summary>
        /// 序列化DataTable,
        /// </summary>
        /// <param name="aTable">需要序列化的DataTable</param>
        /// <returns>成功返回非空字符串</returns>
        public static string SerializerToXml(DataTable aTable)
        {
            StringBuilder sb = new StringBuilder();
            if (aTable == null)
                return "";
 
            System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(System.Data.DataTable));
            System.Xml.XmlWriter writer = System.Xml.XmlWriter.Create(sb);
            serializer.Serialize(writer, aTable);
 
            return sb.ToString();
        }
 
        /// <summary>
        /// 反序列化DataTable表
        /// </summary>
        /// <param name="aXmlData">需要反序列化的DataTable的数据</param>
        /// <returns>成功返回DataTable,失败返回null</returns>
        public static DataTable DeSerializerFromXml(string aXmlData)
        {
            if (string.IsNullOrEmpty(aXmlData))
                return null;
 
            System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(System.Data.DataTable));
            return (DataTable)serializer.Deserialize(new StringReader(aXmlData));
        }
 
        /*
            // 字符串进行16进制编码[decodeSTR],因为编码后位数不等,为了节约空间不进行等长操作,所以并以","分隔
            // 与 StringTool.cs的函数相对应
            function EncodeSTR(str) {
                var t = "";
                for (var x = 0; x < str.length; x++) {
                    a = str.charCodeAt(x);
                    if (x != 0) {
                        t += ‘,‘;
                    }
                    t += a.toString(16).toUpperCase();
                }
                return t;
            }
            //字符串[以","分隔]进行16进制解码,编码用[encodeSTR]
            // 与 StringTool.cs的函数相对应
            function DecodeSTR(str) {
                var a1 = str.split(‘,‘);
                for (var x = 0; x < a1.length; x++) {
                    a1[x] = String.fromCharCode(parseInt(a1[x], 16).toString(10));
                }
                return a1.join(‘‘);
            }
         */
        /// <summary>
        /// 字符串转为用,分隔的16进制字符串 解码用[decodeSTR] 与 StringTool.js的函数相对应
        /// </summary>
        /// <param name="str">字符串</param>
        /// <param name="uppercase">大小写</param>
        /// <returns>失败返回空字符串</returns>
        static public string EncodeSTR(string str, bool uppercase = true)
        {
            if (string.IsNullOrEmpty(str))
                return "";
            Char[] aa = str.ToCharArray();
            StringBuilder sb = new StringBuilder();
            string strFormat = "{0:" + (uppercase == true ? "X" : "x") + "}";
            for (int i = 0; i < str.Length; i++)
            {
                sb.Append(String.Format(strFormat, Char.ConvertToUtf32(str, i)));
                sb.Append(",");
            }
            if (sb.Length > 0)
                sb.Remove(sb.Length - 1, 1);
            return sb.ToString();
        }
 
        /// <summary>
        /// 用,分隔的16进制字符串转为字符串 编码用[EncodeSTR] 与 StringTool.js的函数相对应
        /// </summary>
        /// <param name="str">用,分隔的16进制字符串</param>
        /// <returns>失败返回空字符串</returns>
        static public string DecodeSTR(string str)
        {
            if (string.IsNullOrEmpty(str))
                return "";
            string[] aHexString = str.Split(new char[] { , });
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < aHexString.Length; i++)
            {
                sb.Append(Char.ConvertFromUtf32(Convert.ToInt32(aHexString[i], 16)));
            }
            return sb.ToString();
        }
 
        /// <summary>
        /// 将字符串转为16进制字符串,并进行了异或加密
        /// </summary>
        /// <param name="aStr"></param>
        /// <returns></returns>
        public static string StringToHexString(string aStr)
        {
            if (string.IsNullOrEmpty(aStr))
                return "";
            byte[] b = Encoding.Unicode.GetBytes(EncryptXOR(aStr));
            return ArrayToHexString(b);
        }
 
        /// <summary>
        /// 将16进制字符串转为字符串,并进行了异或解密
        /// </summary>
        /// <param name="aStr"></param>
        /// <returns></returns>
        public static string HexStringToString(string aStr)
        {
            if (string.IsNullOrEmpty(aStr))
                return "";
            byte[] b = HexStringToArray(aStr);
            return DecryptXOR(Encoding.Unicode.GetString(b));
        }
 
        /// <summary>
        /// 字节数组到16进制字符串
        /// </summary>
        /// <param name="array"></param>
        /// <param name="uppercase">大小写</param>
        /// <returns>失败返回空字符串</returns>
        /// 
        static public string ArrayToHexString(byte[] array, bool uppercase = true)
        {
            if (array == null || array.Length < 1) return "";
            string  format = "x2";
            if (uppercase) format = "X2";
            StringBuilder sb = new StringBuilder();
            foreach (byte b in array) sb.Append(b.ToString(format));
            return sb.ToString();
        }
 
        /// <summary>
        ///  将16进制字符串转为字节数组
        /// </summary>
        /// <param name="aHexString"></param>
        /// <param name="uppercase"></param>
        /// <returns></returns>
        static public byte[] HexStringToArray(string aHexString, bool uppercase = true)
        {
            if (string.IsNullOrEmpty(aHexString))
                return null;
            int count = aHexString.Length / 2;
            byte[] b = new byte[count];
            for (int i = 0; i < count; i++)
            {
                string s = aHexString.Substring(i * 2, 2);
                b[i] = byte.Parse(s, System.Globalization.NumberStyles.HexNumber);
            }
 
            return b;
        }
 
        /// <summary>
        /// 在unicode 字符串中,中文的范围是在4E00..9FFF
        //  通过对字符的unicode编码进行判断来确定字符是否为中文。
        /// </summary>
        /// <param name="word"></param>
        /// <returns></returns>
        static public bool IsChineseLetter(string word)
        {
            int code = 0;
            int chfrom = Convert.ToInt32("4e00", 16);    //范围(0x4e00~0x9fff)转换成int(chfrom~chend)
            int chend = Convert.ToInt32("9fff", 16);
            if (word != "")
            {
                code = Char.ConvertToUtf32(word, 0);   //获得字符word中指定索引index处字符unicode编码
                if (code >= chfrom && code <= chend)
                    return true;     //当code在中文范围内返回true
                else
                    return false;    //当code不在中文范围内返回false
            }
            return false;
        }
 
        /// <summary>
        /// 判断句子中是否含有中文
        /// </summary>
        /// <param >字符串</param>
        /// <returns></returns>
        static public bool WordsInChinese(string aStr)
        {
            Regex rx = new Regex("^[\u4e00-\u9fa5]$");
            for (int i = 0; i < aStr.Length; i++)
            {
                if (rx.IsMatch(aStr[i].ToString()))
                    return true;
            }
            return false;
        }
 
        /// <summary>
        /// 给定一个字符串,判断其是否只包含有汉字
        /// </summary>
        /// <param name="aStr"></param>
        /// <returns></returns>
        static public bool IsOnlyContainsChinese(string aStr)
        {
            char[] words = aStr.ToCharArray();
            foreach (char word in words)
            {
                if (IsGBCode(word.ToString()) || IsGBKCode(word.ToString()))  // it is a GB2312 or GBK chinese word
                    continue;
                else
                    return false;
            }
            return true;
        }
 
        /// <summary>
        /// 判断一个word是否为GB2312编码的汉字
        /// </summary>
        /// <param name="word"></param>
        /// <returns></returns>
        static public bool IsGBCode(string word)
        {
            byte[] bytes = Encoding.GetEncoding("GB2312").GetBytes(word);
            if (bytes.Length <= 1)  // if there is only one byte, it is ASCII code or other code
                return false;
            else
            {
                byte byte1 = bytes[0];
                byte byte2 = bytes[1];
                if (byte1 >= 176 && byte1 <= 247 && byte2 >= 160 && byte2 <= 254)    //判断是否是GB2312
                    return true;
                else
                    return false;
            }
        }
 
        /// <summary>
        /// 判断一个word是否为GBK编码的汉字
        /// </summary>
        /// <param name="word"></param>
        /// <returns></returns>
        static public bool IsGBKCode(string word)
        {
            byte[] bytes = Encoding.GetEncoding("GBK").GetBytes(word.ToString());
            if (bytes.Length <= 1)  // if there is only one byte, it is ASCII code
                return false;
            else
            {
                byte byte1 = bytes[0];
                byte byte2 = bytes[1];
                if (byte1 >= 129 && byte1 <= 254 && byte2 >= 64 && byte2 <= 254)     //判断是否是GBK编码
                    return true;
                else
                    return false;
            }
        }
 
        /// <summary>
        /// 判断一个word是否为Big5编码的汉字
        /// </summary>
        /// <param name="word"></param>
        /// <returns></returns>
        static public bool IsBig5Code(string word)
        {
            byte[] bytes = Encoding.GetEncoding("Big5").GetBytes(word.ToString());
            if (bytes.Length <= 1)  // if there is only one byte, it is ASCII code
                return false;
            else
            {
                byte byte1 = bytes[0];
                byte byte2 = bytes[1];
                if ((byte1 >= 129 && byte1 <= 254) && ((byte2 >= 64 && byte2 <= 126) || (byte2 >= 161 && byte2 <= 254)))  //判断是否是Big5编码
                    return true;
                else
                    return false;
            }
        }
 
        /// <summary>
        /// 对字符串进行简单的异或加密
        /// </summary>
        /// <param name="aStr"></param>
        /// <param name="aXor"></param>
        /// <returns>失败返回空字符串</returns>
        static public string EncryptXOR(string aStr, byte aXor = 0x11)
        {
            if (String.IsNullOrEmpty(aStr))
                return "";
            byte[] bb = Encoding.Unicode.GetBytes(aStr);
            for (int i = 0; i < bb.Length; i++)
                bb[i] ^= aXor;
            return Encoding.Unicode.GetString(bb);
        }
 
        /// <summary>
        /// 对字符串进行简单的异或解密
        /// </summary>
        /// <param name="aStr"></param>
        /// <param name="aXor"></param>
        /// <returns>失败返回空字符串</returns>
        static public string DecryptXOR(string aStr, byte aXor = 0x11)
        {
            if (String.IsNullOrEmpty(aStr))
                return "";
            byte[] bb = Encoding.Unicode.GetBytes(aStr);
            for (int i = 0; i < bb.Length; i++)
                bb[i] ^= aXor;
            return Encoding.Unicode.GetString(bb);
        }
 
        /// <summary>
        /// 获得字符串中开始和结束字符串中间得字符
        /// </summary>
        /// <param name="str">字符串</param>
        /// <param name="s">开始</param>
        /// <param name="e">结束</param>
        /// </summary>
        public static string GetSubString(string str, string s, string e)
        {
            Regex rg = new Regex("(?<=(" + s + "))[.\\s\\S]*?(?=(" + e + "))", RegexOptions.Multiline | RegexOptions.Singleline);
            return rg.Match(str).Value;
        }
 
        /// <summary>
        /// 从最后一位验证前面17位的18位身份证号码
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public static bool CheckCardId(string id)
        {
            /*  身份证号码的验证及15位升18位算法
                 18位身份证标准在国家质量技术监督局于1999年7月1日实施的GB11643-1999《公民身份号码》中做了明确的规定。 GB11643-1999《公民身份号码》为GB11643-1989《社会保障号码》的修订版,其中指出将原标准名称"社会保障号码"更名为"公民身份号码",另外GB11643-1999《公民身份号码》从实施之日起代替GB11643-1989。GB11643-1999《公民身份号码》主要内容如下: 
                一、范围 
                     该标准规定了公民身份号码的编码对象、号码的结构和表现形式,使每个编码对象获得一个唯一的、不变的法定号码。 
                二、编码对象 
                     公民身份号码的编码对象是具有中华人民共和国国籍的公民。 
                三、号码的结构和表示形式 
                1、号码的结构 
                    公民身份号码是特征组合码,由十七位数字本体码和一位校验码组成。排列顺序从左至右依次为:六位数字地址码,八位数字出生日期码,三位数字顺序码和一位数字校验码。 
                2、地址码 
                    表示编码对象常住户口所在县(市、旗、区)的行政区划代码,按GB/T2260的规定执行。 
                3、出生日期码 
                    表示编码对象出生的年、月、日,按GB/T7408的规定执行,年、月、日代码之间不用分隔符。 
                4、顺序码 
                     表示在同一地址码所标识的区域范围内,对同年、同月、同日出生的人编定的顺序号,顺序码的奇数分配给男性,偶数分配给女性。 
                5、校验码 
                (1)十七位数字本体码加权求和公式 
                    S = Sum(Ai * Wi),先对前17位数字的权求和 
                    Ai:表示第i位置上的身份证号码数字值 
                    Wi:表示第i位置上的加权因子 
                    Wi: 7 9 10 5 8 4 2 1 6 3 7 9 10 5 8 4 2 
                (2)计算模         Y = mod(S, 11) 
                (3)通过模得到对应的校验码 
                    Y:      0 1 2 3 4 5 6 7 8 9 10 
                    校验码: 1 0 X 9 8 7 6 5 4 3 2 
                四、举例如下: 
                北京市朝阳区: 11010519491231002X 
                广东省汕头市: 440524188001010014 
            */
 
            int[] wQuan = { 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2 };
            string checkWei = "10X98765432";
 
            string number17 = id.Substring(0, 17);
            string number18 = id.Substring(17);
 
            int sum = 0;
            for (int i = 0; i < 17; i++)
                sum = sum + Convert.ToInt32(number17[i].ToString()) * wQuan[i];
 
            int mod = sum % 11;
            string result = checkWei[mod].ToString();
            if (number18.Equals(result, StringComparison.OrdinalIgnoreCase))
            {
                return true;
            }
            else
            {
                return false;
            }
        }
 
        /// <summary>
        /// 生成一个序列号,根据Guid生成,最短1位,最长33位,默认是4位
        /// </summary>
        /// <param name="aLength"></param>
        /// <returns></returns>
        public static string CreateSerialNumber(int aLength = 4)
        {
            if (aLength < 1)
                aLength = 1;
            if (aLength > 33)
                aLength = 33;
 
            string str = string.Empty;
            string codeStr = string.Empty;
            string guidStr = Guid.NewGuid().ToString().Replace("-", "");
            int guidStrLen = guidStr.Length;
            Random rnd = new Random(int.Parse(DateTime.Now.ToString("MMddHHmmsss")));
 
            for (int i = 0; i < aLength; i++)
            {
                int index = rnd.Next(0, guidStrLen - 1);
                str += guidStr.Substring(index, 1);
            }
 
            return str.ToUpper();
        }
 
        /// <summary>
        /// 反转字符串
        /// </summary>
        /// <param name="aString"></param>
        /// <returns></returns>
        public static string ReverseString(string aString)
        {
            if (string.IsNullOrEmpty(aString))
                return "";
            Char[] LS_Str = aString.ToCharArray();
            Array.Reverse(LS_Str);
 
            return new String(LS_Str);//反转字符串
        }
 
        /// <summary>
        /// 全角转半角
        /// </summary>
        /// <param name="aString"></param>
        /// <returns></returns>
        public static string QjToBj(string aString)
        {
            string QJstr = aString;
            char[] c = QJstr.ToCharArray();
            for (int i = 0; i < c.Length; i++)
            {
                byte[] b = System.Text.Encoding.Unicode.GetBytes(c, i, 1);
                if (b.Length == 2)
                {
                    if (b[1] == 255)
                    {
                        b[0] = (byte)(b[0] + 32);
                        b[1] = 0;
                        c[i] = System.Text.Encoding.Unicode.GetChars(b)[0];
                    }
                }
            }
            string strNew = new string(c);
            return strNew;
        }
 
        /// <summary>
        /// 获得汉字拼音的的第一个字母
        /// </summary>
        /// <param name="aText"></param>
        /// <returns></returns>
        static public string GetChineseSpellFirstLetter(string aText)
        {
            int len = aText.Length;
            string myStr = "";
            for (int i = 0; i < len; i++)
            {
                myStr += GetSpell(aText[i]);
            }
            return myStr.ToLower();
        }
 
        /// <summary>
        /// 利用汉字在计算机里面的编码来的到汉字的拼音。
        /// </summary>
        /// <param name="aChar"></param>
        /// <returns></returns>
        static public string GetSpell(char aChar)
        {
            byte[] arrCN = Encoding.Default.GetBytes(aChar.ToString());
            if (arrCN.Length > 1)
            {
                int area = (short)arrCN[0];
                int pos = (short)arrCN[1];
                int code = (area << 8) + pos;
                int[] areacode = { 45217, 45253, 45761, 46318, 46826, 47010, 47297, 47614, 48119, 48119, 49062, 49324, 49896, 50371, 50614, 50622, 50906, 51387, 51446, 52218, 52698, 52698, 52698, 52980, 53689, 54481 };
                for (int i = 0; i < 26; i++)
                {
                    int max = 55290;
                    if (i != 25) max = areacode[i + 1];
                    if (areacode[i] <= code && code < max)
                    {
                        return Encoding.Default.GetString(new byte[] { (byte)(65 + i) });
                    }
                }
                return aChar.ToString();
            }
            else
                return aChar.ToString();
        }
    }

 

字符串处理增强类

标签:

原文地址:http://www.cnblogs.com/rinack/p/4624145.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!