C#常用字符串操作类处理与归纳

导读:本篇文章讲解 C#常用字符串操作类处理与归纳,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com

常用–字符串操作类(整理与归纳)
1、判断对象是否为空,为空返回true
2、把字符串按分隔符拆成List
3、把List按分隔符合成字符串
4、DelChar 以指定字符去尾或去头
5、IsMatch 快速验证一个字符串是否符合指定的正则表达式
6、ISNumber 验证字符串是否纯数字
7、MD5 对字符串进行MD5加密
8、DES 加密
9、DES 解密

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace MyTools
{
    /// <summary>
    /// 字符串操作类
    /// 1、判断对象是否为空,为空返回true
    /// 2、把字符串按分隔符拆成List
    /// 3、把List按分隔符合成字符串
    /// 4、DelChar 以指定字符去尾或去头
    /// 5、IsMatch 快速验证一个字符串是否符合指定的正则表达式
    /// 6、ISNumber 验证字符串是否纯数字
    /// 7、MD5 对字符串进行MD5加密
    /// 8、DES 加密
    /// 9、DES 解密
    /// </summary>
    public class StringHelp
    {
        #region 1、判断对象是否为空
        /// <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 2、把字符串按分隔符转换成List
        /// <summary>
        /// 把字符串按分隔符拆成List
        /// </summary>
        /// <param name="str">源字符串</param>
        /// <param name="speater">分隔符</param>
        /// <param name="toLower">是否转换为小写</param>
        /// <param name="toUnique">是否去重复</param>
        public static List<string> StrToList(string str, char speater, bool toLower = false, bool toUnique = false)
        {
            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();
                    }
                    if (toUnique)
                    {
                        if (!list.Contains(strVal)) list.Add(strVal);
                    }
                    else
                    {
                        list.Add(strVal);
                    }
                }
            }
            return list;
        }
        #endregion

        #region 3、把数组按分隔符拼成字符串
        /// <summary>
        /// 把List按分隔符合成字符串
        /// </summary>
        /// <param name="list">源数组</param>
        /// <param name="speater">分隔符</param>
        public static string ListToStr(List<string> list, char speater = ',')
        {
            StringBuilder sb = new StringBuilder();
            int i = 1;
            foreach (string ss in list)
            {
                sb.Append(ss);
                if (i < list.Count) sb.Append(speater);//最后不需要添加
                i++;
            }
            return sb.ToString();
        }
        #endregion

        #region 4、以指定字符去尾或去头
        /// <summary>
        /// 以指定字符去尾或去头
        /// </summary>
        /// <param name="str">源字符</param>
        /// <param name="strchar">指定字符</param>
        /// <param name="FirstOrLast">true,去尾;false,去头</param>
        public static string DelChar(string str, string strchar, bool FirstOrLast = true)
        {
            if (FirstOrLast)
            {
                return str.Substring(0, str.LastIndexOf(strchar));
            }
            else
            {
                return str.Substring(str.IndexOf(strchar) + 1);
            }
        }
        #endregion

        #region 5、快速验证一个字符串是否符合指定的正则表达式
        /// <summary>
        /// 快速验证一个字符串是否符合指定的正则表达式
        /// </summary>
        /// <param name="pattern">正则表达式的内容</param>
        /// <param name="strVal">需验证的字符串</param>
        public static bool IsMatch(string pattern, string strVal)
        {
            if (strVal == null) return false;
            Regex myRegex = new Regex(pattern);
            if (strVal.Length == 0) return false;
            return myRegex.IsMatch(strVal);
        }
        #endregion

        #region 6、验证字符串是否纯数字
        /// <summary>
        /// 验证字符串是否纯数字
        /// </summary>
        /// <param name="_value">需验证字符串</param>
        /// <param name="Topoint">是否含有小数点</param>
        public static bool IsNumber(string _value, bool Topoint = false)
        {
            if (Topoint)
            {
                return IsMatch("^[1-9]*[0-9]*$", _value);
            }
            else
            {
                return IsMatch(@"^[1-9]\d{0,7}(\.\d{1,6})?$", _value);
            }
        }
        #endregion

        #region 7、对字符串进行MD5加密
        /// <summary>
        /// 对字符串进行MD5加密
        /// </summary>
        /// <param name="str">源字符串</param>
        public static string MD5Encrypt(string str)
        {
            MD5 MD = new MD5CryptoServiceProvider();
            byte[] b = MD.ComputeHash(Encoding.UTF8.GetBytes(str));
            string Result = BitConverter.ToString(b);
            Result = Result.Replace("-", "");
            return Result.Substring(8, 16);
        }
        #endregion

        #region 8、DES加密
        /// <summary>
        /// DES加密
        /// </summary>
        /// <param name="pToEncrypt">加密字符串</param>
        /// <param name="sKey">密钥</param>
        public static string DESEncrypt(string pToEncrypt, string sKey)
        {
            if (pToEncrypt == "") return "";
            if (sKey.Length < 8) sKey = sKey + "xuE29xWp";
            if (sKey.Length > 8) sKey = sKey.Substring(0, 8);
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();
            //把字符串放到byte数组中  
            //原来使用的UTF8编码,我改成Unicode编码了,不行  
            byte[] inputByteArray = Encoding.Default.GetBytes(pToEncrypt);
            //建立加密对象的密钥和偏移量  
            //原文使用ASCIIEncoding.ASCII方法的GetBytes方法  
            //使得输入密码必须输入英文文本  
            des.Key = ASCIIEncoding.Default.GetBytes(sKey);
            des.IV = ASCIIEncoding.Default.GetBytes(sKey);
            MemoryStream ms = new MemoryStream();
            CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
            //Write  the  byte  array  into  the  crypto  stream  
            //(It  will  end  up  in  the  memory  stream)  
            cs.Write(inputByteArray, 0, inputByteArray.Length);
            cs.FlushFinalBlock();
            //Get  the  data  back  from  the  memory  stream,  and  into  a  string  
            StringBuilder ret = new StringBuilder();
            foreach (byte b in ms.ToArray())
            {
                //Format  as  hex  
                ret.AppendFormat("{0:X2}", b);
            }
            ret.ToString();
            return ret.ToString();
        }
        #endregion

        #region 9、DES解密
        /// <summary>
        /// DES解密
        /// </summary>
        /// <param name="pToDecrypt">解密字符串</param>
        /// <param name="sKey">解密密钥</param>
        /// <param name="outstr">返回值</param>
        public static bool DESDecrypt(string pToDecrypt, string sKey, out string outstr)
        {
            if (pToDecrypt == "")
            {
                outstr = "";
                return true;
            };
            if (sKey.Length < 8) sKey = sKey + "xuE29xWp";
            if (sKey.Length > 8) sKey = sKey.Substring(0, 8);
            try
            {
                DESCryptoServiceProvider des = new DESCryptoServiceProvider();
                //Put  the  input  string  into  the  byte  array  
                byte[] inputByteArray = new byte[pToDecrypt.Length / 2];
                for (int x = 0; x < pToDecrypt.Length / 2; x++)
                {
                    int i = (Convert.ToInt32(pToDecrypt.Substring(x * 2, 2), 16));
                    inputByteArray[x] = (byte)i;
                }
                //建立加密对象的密钥和偏移量,此值重要,不能修改  
                des.Key = ASCIIEncoding.Default.GetBytes(sKey);
                des.IV = ASCIIEncoding.Default.GetBytes(sKey);
                MemoryStream ms = new MemoryStream();
                CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
                //Flush  the  data  through  the  crypto  stream  into  the  memory  stream  
                cs.Write(inputByteArray, 0, inputByteArray.Length);
                cs.FlushFinalBlock();
                //Get  the  decrypted  data  back  from  the  memory  stream  
                //建立StringBuild对象,CreateDecrypt使用的是流对象,必须把解密后的文本变成流对象  
                StringBuilder ret = new StringBuilder();
                outstr = System.Text.Encoding.Default.GetString(ms.ToArray());
                return true;
            }
            catch
            {
                outstr = "";
                return false;
            }
        }
        #endregion
    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由半码博客整理,本文链接:https://www.bmabk.com/index.php/post/107126.html

(0)
小半的头像小半

相关推荐

半码博客——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!