1. 程式人生 > 其它 >C#常用字串操作類處理與歸納

C#常用字串操作類處理與歸納

技術標籤:C#語法與應用c#字串

常用–字串操作類(整理與歸納)
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 } }