博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
自制常用工具类Common
阅读量:4328 次
发布时间:2019-06-06

本文共 39458 字,大约阅读时间需要 131 分钟。

using System;using System.Collections.Generic;using System.Drawing;using System.IO;using System.Linq;using System.Security.Cryptography;using System.Text;using System.Text.RegularExpressions;using System.Web;using System.Drawing.Imaging;using System.Net;using System.Drawing.Drawing2D;using System.Xml;using System.Collections;namespace xxxxxxx{        public class Common    {    
///         /// 隐藏文字        ///         ///         /// 显示首尾几位        /// 例子:HideName("13912345678",3)=> 139*****678        /// 
public static string HideString(string name, int showcount = 1) { string str = ""; Func
go = (num) => { string s = ""; for (int i = 0; i < num; i++) { s += "*"; } return s; }; switch (name.Length) { case 0: case 1: str = name; break; case 2: str = "*" + name.Substring(1); break; default: str = name.Substring(0, showcount) + go(name.Length - (showcount * 2)) + name.Substring(name.Length - showcount); break; } return str; }
 

 

///         /// 序号添0补充        ///         /// 序号        /// 序号长度        /// generate_number(123,5)=>00123        /// 
public static string generate_number(int num, int length = 5) { //如果序号长度大于长度 默认为数字长度 if (num.ToString().Length > length) { length = num.ToString().Length; } string strs = ""; for (int i = 0; i < length - num.ToString().Length; i++) strs += "0"; return strs + num.ToString(); }

 

///         /// Object转换String        ///         ///         /// 
public static string ObjectToString(object session) { return session == null ? "" : session.ToString(); } /// /// Object转换Int /// /// ///
public static int ObjectToInt(object session) { int num = -1; int.TryParse(session == null ? "" : session.ToString(), out num); return num; } /// /// Object转换Decimal /// /// ///
public static decimal ObjectToDecimal(object session) { decimal num = -1; decimal.TryParse(session == null ? "" : session.ToString(), out num); return num; } /// /// Object转换DateTime 时间格式转换 时间格式错误|默认1970-01-01 /// /// ///
public static DateTime ObjectToDateTime(object session) { DateTime num = DateTime.Parse("1970-01-01"); DateTime.TryParse(session == null ? null : session.ToString(), out num); return num; } /// /// Object转换Bool /// /// ///
public static bool ObjectToBool(object session) { bool buf = false; bool.TryParse(session == null ? "" : session.ToString(), out buf); return buf; } /// /// 图片转Base64 /// /// ///
public static string GetBase64FromImage(string imagefile) { string strbaser64 = ""; try { Bitmap bmp = new Bitmap(imagefile); strbaser64 = GetBase64FromImage(bmp).base64; } catch (Exception) { throw new Exception("Something wrong during convert!"); } return strbaser64; } /// /// 图片转Base64 /// /// ///
public static Base64Class GetBase64FromImage(Bitmap bmp) { Base64Class base64Class = new Base64Class(); try { MemoryStream ms = new MemoryStream(); bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg); byte[] arr = new byte[ms.Length]; ms.Position = 0; ms.Read(arr, 0, (int)ms.Length); ms.Close(); base64Class.base64 = Convert.ToBase64String(arr); base64Class.width = bmp.Width; base64Class.height = bmp.Height; } catch (Exception) { throw new Exception("Something wrong during convert!"); } return base64Class; } public class Base64Class { /// /// 图片base64 /// public string base64 { get; set; } /// /// 宽 /// public int width { get; set; } /// /// 高 /// public int height { get; set; } } /// /// Base64 转 图片 /// /// ///
public static Bitmap GetImageFromBase64(string base64string) { byte[] b = Convert.FromBase64String(base64string); MemoryStream ms = new MemoryStream(b); Bitmap bitmap = new Bitmap(ms); return bitmap; } /// /// Base64 转 流 /// /// ///
public static MemoryStream Base64ToMemo(string base64string) { byte[] b = Convert.FromBase64String(base64string); MemoryStream ms = new MemoryStream(b); ms.Position = 0; return ms; } /// /// 将 Stream 转成 byte[] /// /// ///
public static byte[] StreamToBytes(Stream stream) { byte[] bytes = new byte[stream.Length]; stream.Read(bytes, 0, bytes.Length); // 设置当前流的位置为流的开始 stream.Seek(0, SeekOrigin.Begin); return bytes; } /// /// 递归删除 文件 文件夹 /// /// public static void RecursiveDel(string directoryUrl) { if (Directory.Exists(directoryUrl)) { //当前目录所有文件 foreach (var file in Directory.GetFiles(directoryUrl)) if (File.Exists(file)) File.Delete(file); //当前目录中所有目录 //递归删除 foreach (var dire in Directory.GetDirectories(directoryUrl)) RecursiveDel(dire); Directory.Delete(directoryUrl); } } /// /// DateTime时间格式转换为Unix时间戳格式 /// /// DateTime时间格式 ///
Unix时间戳格式
public static int ConvertDateTimeInt(System.DateTime time) { System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1)); return (int)(time - startTime).TotalSeconds; } /// /// 判断UserAgent设备 /// /// ///
public static string CheckAnget(string ua) { string[] keywords = { "Android", "iPhone", "iPod", "iPad", "Windows Phone", "MQQBrowser" }; string[] pckeyword = { "Windows NT", "Macintosh" }; if (ua.Contains("Windows NT")) { //return "Windows"; return "PC"; } else if (ua.Contains("Macintosh")) { //return "OS X"; return "苹果"; } else { foreach (var item in keywords) { if (ua.Contains(item)) { //return item; return "手机"; } } } return ua; } /// /// 保留几位小数取小数点 非四舍五入 /// ///
public static decimal DecimalPointNotRound(object num, int count = 2) { decimal _n = 0; if (!decimal.TryParse(num.ToString(), out _n)) return _n; Regex re = new Regex(@"-?\d*(\.\d{
" + count + "})?"); var match = re.Match(num.ToString()); return decimal.Parse(match.Value); } ///移除HTML标签 /// /// 移除HTML标签 /// /// HTMLStr public static string ParseTags(string HTMLStr) { return System.Text.RegularExpressions.Regex.Replace(HTMLStr, "<[^>]*>", ""); } /// 取出文本中的图片地址 /// 取出文本中的图片地址 /// /// 取出文本中的图片地址 /// /// HTMLStr public static string GetImgUrl(string HTMLStr) { string str = string.Empty; string sPattern = @"^
]*>"; Regex r = new Regex(@"
]*\s*src\s*=\s*([']?)(?
\S+)'?[^>]*>", RegexOptions.Compiled); Match m = r.Match(HTMLStr.ToLower()); if (m.Success) str = m.Result("${url}"); return str; } ///
/// 加密 /// ///
///
密钥必须是8位 ///
public static string MD5Encrypt(string pToEncrypt, string sKey) { DESCryptoServiceProvider des = new DESCryptoServiceProvider(); byte[] inputByteArray = Encoding.Default.GetBytes(pToEncrypt); des.Key = ASCIIEncoding.ASCII.GetBytes(sKey); des.IV = ASCIIEncoding.ASCII.GetBytes(sKey); MemoryStream ms = new MemoryStream(); CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write); cs.Write(inputByteArray, 0, inputByteArray.Length); cs.FlushFinalBlock(); StringBuilder ret = new StringBuilder(); foreach (byte b in ms.ToArray()) { ret.AppendFormat("{0:X2}", b); } ret.ToString(); return ret.ToString(); } ///
/// 解密 /// ///
///
///
public static string MD5Decrypt(string pToDecrypt, string sKey) { string text = ""; try { DESCryptoServiceProvider des = new DESCryptoServiceProvider(); 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.ASCII.GetBytes(sKey); des.IV = ASCIIEncoding.ASCII.GetBytes(sKey); MemoryStream ms = new MemoryStream(); CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write); cs.Write(inputByteArray, 0, inputByteArray.Length); cs.FlushFinalBlock(); StringBuilder ret = new StringBuilder(); text = System.Text.Encoding.Default.GetString(ms.ToArray()); } catch { text = pToDecrypt; } return text; } ///
/// 加密 /// ///
要加密的字符串,即明文 ///
公共密钥 ///
是否使用MD5生成机密秘钥 ///
加密后的字符串,即密文
public static string Encrypt(string toEncrypt, string key, bool useHashing) { try { byte[] keyArray; byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(toEncrypt); if (useHashing) { MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider(); keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key)); } else keyArray = UTF8Encoding.UTF8.GetBytes(key); TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider(); tdes.Key = keyArray; tdes.Mode = CipherMode.ECB; tdes.Padding = PaddingMode.PKCS7; ICryptoTransform cTransform = tdes.CreateEncryptor(); byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length); return Convert.ToBase64String(resultArray, 0, resultArray.Length); } catch { } return string.Empty; } ///
/// 解密 /// ///
要解密的字符串,即密文 ///
公共密钥 ///
是否使用MD5生成机密密钥 ///
解密后的字符串,即明文
public static string Decrypt(string toDecrypt, string key, bool useHashing) { try { byte[] keyArray; byte[] toEncryptArray = Convert.FromBase64String(toDecrypt); if (useHashing) { MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider(); keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key)); } else keyArray = UTF8Encoding.UTF8.GetBytes(key); TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider(); tdes.Key = keyArray; tdes.Mode = CipherMode.ECB; tdes.Padding = PaddingMode.PKCS7; ICryptoTransform cTransform = tdes.CreateDecryptor(); byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length); return UTF8Encoding.UTF8.GetString(resultArray); } catch { } return string.Empty; } ///
/// 删除文本中的图片 /// ///
public static void DeleteContentImg(string content) { var matches = Regex.Matches(content, @"
<>]*?\bsrc[\s\t\r\n]*=[\s\t\r\n]*[""']?[\s\t\r\n]*(?
[^\s\t\r\n""'<>]*)[^<>]*?/?[\s\t\r\n]*>"); foreach (Match match in matches) { string imgpath = match.Groups["imgUrl"].Value; } } ///
/// 图片缩放 /// ///
///
///
///
public static Bitmap ImgThumbnail(Bitmap b, int destHeight, int destWidth) { System.Drawing.Image imgSource = b; System.Drawing.Imaging.ImageFormat thisFormat = imgSource.RawFormat; int sW = 0, sH = 0; // 按比例缩放 int sWidth = imgSource.Width; int sHeight = imgSource.Height; if (sHeight > destHeight || sWidth > destWidth) { if ((sWidth * destHeight) > (sHeight * destWidth)) { sW = destWidth; sH = (destWidth * sHeight) / sWidth; } else { sH = destHeight; sW = (sWidth * destHeight) / sHeight; } } else { sW = sWidth; sH = sHeight; } Bitmap outBmp = new Bitmap(destWidth, destHeight); Graphics g = Graphics.FromImage(outBmp); g.Clear(Color.Transparent); // 设置画布的描绘质量 g.CompositingQuality = CompositingQuality.HighQuality; g.SmoothingMode = SmoothingMode.HighQuality; g.InterpolationMode = InterpolationMode.HighQualityBicubic; g.DrawImage(imgSource, new Rectangle((destWidth - sW) / 2, (destHeight - sH) / 2, sW, sH), 0, 0, imgSource.Width, imgSource.Height, GraphicsUnit.Pixel); g.Dispose(); // 以下代码为保存图片时,设置压缩质量 EncoderParameters encoderParams = new EncoderParameters(); long[] quality = new long[1]; quality[0] = 100; EncoderParameter encoderParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality); encoderParams.Param[0] = encoderParam; imgSource.Dispose(); return outBmp; } ///
/// 下载文件 /// ///
///
public static MemoryStream DownloadFile(string url) { Uri uri = new Uri(url.Replace("\\", "/")); WebRequest request = WebRequest.Create(uri); WebResponse response = request.GetResponse(); Stream stream = response.GetResponseStream(); MemoryStream ms = new MemoryStream(); Byte[] buffer = new Byte[1024]; int current = 0; while ((current = stream.Read(buffer, 0, buffer.Length)) != 0) { ms.Write(buffer, 0, current); } return ms; } ///
/// 下载图片 /// ///
///
public static Bitmap DownloadImg(string url) { Bitmap bit = null; try { Uri uri = new Uri(url.Replace("\\", "/")); WebRequest request = WebRequest.Create(uri); WebResponse response = request.GetResponse(); Stream stream = response.GetResponseStream(); MemoryStream ms = new MemoryStream(); Byte[] buffer = new Byte[1024]; int current = 0; while ((current = stream.Read(buffer, 0, buffer.Length)) != 0) { ms.Write(buffer, 0, current); } bit = new Bitmap(ms); } catch { } return bit; } ///
/// 剪裁 -- 用GDI+ /// ///
原始Bitmap ///
开始坐标X ///
开始坐标Y ///
宽度 ///
高度 ///
剪裁后的Bitmap
public static Bitmap Cut(Bitmap b, int StartX, int StartY, int iWidth, int iHeight) { if (b == null) { return null; } int w = b.Width; int h = b.Height; if (StartX >= w || StartY >= h) { return null; } if (StartX + iWidth > w) { iWidth = w - StartX; } if (StartY + iHeight > h) { iHeight = h - StartY; } try { Bitmap bmpOut = new Bitmap(iWidth, iHeight, PixelFormat.Format24bppRgb); Graphics g = Graphics.FromImage(bmpOut); Rectangle destRect = new Rectangle(0, 0, iWidth, iHeight);//显示图像的位置 Rectangle srcRect = new Rectangle(StartX, StartY, iWidth, iHeight);//显示图像那一部分 GraphicsUnit units = GraphicsUnit.Pixel;//源矩形的度量单位设置为像素 g.DrawImage(b, destRect, srcRect, units); g.Dispose(); return bmpOut; } catch { return null; } } ///
/// 图片剪切 /// ///
///
///
///
偏移X ///
偏移Y ///
public static Bitmap BitmapCut(Bitmap bit, int iWidth = 100, int iHeight = 100, int StartX = 0, int StartY = 0) { int sWidth = iWidth; int sHeight = iHeight; if (bit.Width > bit.Height) //宽处理 { int w = int.Parse(((bit.Width / (double)bit.Height) * iHeight).ToString("0")); if (w > iWidth) sWidth = w; else sHeight = int.Parse((iHeight / (bit.Width / (double)bit.Height)).ToString("0")); } else if (bit.Height > bit.Width) { int h = int.Parse(((bit.Height / (double)bit.Width * bit.Width)).ToString("0")); if (h > iHeight) sHeight = h; } int strY = ((bit.Height - iHeight) / 2) + StartY; int strX = ((bit.Width - iWidth) / 2) + StartX; bit = Common.Cut(bit, strX, strY, iWidth, iHeight); return bit; } ///
/// 图片缩略图 /// ///
///
///
///
偏移X ///
偏移Y ///
public static Bitmap BitmapThumbnail(Bitmap bit, int iWidth = 100, int iHeight = 100, int StartX = 0, int StartY = 0) { int sWidth = iWidth; int sHeight = iHeight; if (bit.Width > bit.Height) //宽处理 { int w = int.Parse(((bit.Width / (double)bit.Height) * iHeight).ToString("0")); if (w > iWidth) sWidth = w; else sHeight = int.Parse((iHeight / (bit.Width / (double)bit.Height)).ToString("0")); } else if (bit.Height > bit.Width) { int h = int.Parse(((bit.Height / (double)bit.Width * bit.Width)).ToString("0")); if (h > iHeight) sHeight = h; } int strY = ((bit.Height - iHeight) / 2) + StartY; int strX = ((bit.Width - iWidth) / 2) + StartX; bit = Common.Cut(bit, strX, strY, iWidth, iHeight); return bit; } ///
/// int获取枚举 /// ///
枚举集合
///
///
public static T NumToEnum
(int num) { foreach (var myCode in Enum.GetValues(typeof(T))) { if ((int)myCode == num) { return (T)myCode; } } throw new ArgumentException(string.Format("{0} 未能找到对应的枚举.", num), "Description"); } ///
/// 获取一个类指定的属性值 /// ///
object对象 ///
属性名称 ///
public static object GetPropertyValue(object info, string field) { if (info == null) return null; Type t = info.GetType(); IEnumerable
property = from pi in t.GetProperties() where pi.Name.ToLower() == field.ToLower() select pi; return property.First().GetValue(info, null); } static int GetRandomSeed() { byte[] bytes = new byte[4]; System.Security.Cryptography.RNGCryptoServiceProvider rng = new System.Security.Cryptography.RNGCryptoServiceProvider(); rng.GetBytes(bytes); return BitConverter.ToInt32(bytes, 0); } ///
/// 随意数 /// ///
随机数位数 ///
public static string GetRandomNum(int num) { StringBuilder str = new StringBuilder(); Random rand = new Random(GetRandomSeed()); for (int i = 0; i < num; i++) { str.Append(rand.Next(0, 9).ToString()); } return str.ToString(); } ///
/// 随机数(带英文) /// ///
///
public static string GenerateRandom(int Length) { char[] constant = { '0','1','2','3','4','5','6','7','8','9', 'a','b','c','d','e','f','g','h','i','j','k','l','m','n','p','q','r','s','t','u','v','w','x','y','z' }; System.Text.StringBuilder newRandom = new System.Text.StringBuilder(62); Random rd = new Random(); for (int i = 0; i < Length; i++) { newRandom.Append(constant[rd.Next(constant.Length)]); } return newRandom.ToString(); } public static string HttpPost2(string Url, string postDataStr, string contentType = "application/x-www-form-urlencoded") { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url); request.Method = "POST"; request.Timeout = 20000; request.KeepAlive = true; request.ContentType = contentType; request.UserAgent = "User-Agent:Mozilla/5.0 (Windows NT 5.1) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/14.0.835.202 Safari/535.1"; byte[] postData = System.Text.Encoding.GetEncoding("gb2312").GetBytes(postDataStr); request.ContentLength = postData.Length; //request.CookieContainer = cookie; Stream myRequestStream = request.GetRequestStream(); //Stream myStreamWriter = new Stream(request.GetRequestStream(), Encoding.GetEncoding("gb2312")); myRequestStream.Write(postData, 0, postData.Length); myRequestStream.Close(); //myStreamWriter.Flush(); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); //response.Cookies = cookie.GetCookies(response.ResponseUri); Stream myResponseStream = response.GetResponseStream(); StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8")); string retString = myStreamReader.ReadToEnd(); myStreamReader.Close(); myResponseStream.Close(); return retString; } ///
/// 间隔时间 刚刚 几分钟前..... /// ///
///
public static string TimeInterval(DateTime date) { string time = ""; var dq = DateTime.Now; var timespan = dq - date; var day = timespan.TotalDays; if (timespan.TotalMinutes < 1) { time = "刚刚"; } else if (timespan.TotalHours < 1) { time = timespan.TotalMinutes.ToString("0") + "分钟前"; } else if (timespan.TotalDays < 1) { time = timespan.TotalHours.ToString("0") + "小时前"; } else if (timespan.TotalDays < 2) { time = "昨天"; } else if (timespan.TotalDays < 3) { time = "前天"; } else if (dq.Year - date.Year <= 0) { time = date.ToString("MM月dd日"); } else if (dq.Year - date.Year > 0) { time = date.ToString("yyyy年MM月dd日"); } else { time = date.ToString(); } return time; } ///
/// 传入URL返回网页的html代码 /// ///
URL ///
public static string getUrltoHtml(string Url) { string errorMsg = ""; try { System.Net.WebRequest wReq = System.Net.WebRequest.Create(Url); // Get the response instance. System.Net.WebResponse wResp = wReq.GetResponse(); // Read an HTTP-specific property //if (wResp.GetType() ==HttpWebResponse) //{ //DateTime updated =((System.Net.HttpWebResponse)wResp).LastModified; //} // Get the response stream. System.IO.Stream respStream = wResp.GetResponseStream(); // Dim reader As StreamReader = New StreamReader(respStream) System.IO.StreamReader reader = new System.IO.StreamReader(respStream, System.Text.Encoding.GetEncoding("gb2312")); return reader.ReadToEnd(); } catch (System.Exception ex) { errorMsg = ex.Message; } return ""; } ///
/// 类赋值 /// ///
///
///
public static void EntityToEntity
(T pTargetObjSrc, T pTargetObjDest) { try { foreach (var mItem in typeof(T).GetProperties()) { mItem.SetValue(pTargetObjDest, mItem.GetValue(pTargetObjSrc, new object[] { }), null); } } catch (NullReferenceException NullEx) { throw NullEx; } catch (Exception Ex) { throw Ex; } } ///
/// 类赋值(两个类属性相似赋值) /// ///
///
///
目标类 ///
源类 public static void EntityToEntity
(T pTargetObjSrc, E pTargetObjDest) { try { foreach (var mItem in typeof(T).GetProperties()) { mItem.SetValue(pTargetObjDest, mItem.GetValue(pTargetObjSrc, new object[] { }), null); } } catch (NullReferenceException NullEx) { throw NullEx; } catch (Exception Ex) { throw Ex; } } #region 类 ///
/// 表单数据项 /// public class FormItemModel { public FormitemTypeEnum formItemType { get; set; } = FormitemTypeEnum.文本; ///
/// 表单键,request["key"] /// public string Key { set; get; } ///
/// 表单值,上传文件时忽略,request["key"].value /// 格式:application/octet-stream /// public string Value { set; get; } public byte[] pic_bytes { get; set; } ///
/// 是否是文件 /// public bool IsFile { get { if (FileContent == null || FileContent.Length == 0) return false; if (FileContent != null && FileContent.Length > 0 && string.IsNullOrWhiteSpace(FileName)) throw new Exception("上传文件时 FileName 属性值不能为空"); return true; } } ///
/// 上传的文件名 /// public string FileName { set; get; } ///
/// 上传的文件内容 /// public Stream FileContent { set; get; } } ///
/// Form上传类型 /// public enum FormitemTypeEnum { 文本 = 0, 文件 = 1, 图片 = 2 } ///
/// (专用)微讯同步上传返回信息 /// public class ZY_MicronewsResult { public string response { get; set; } public ModelError error { get; set; } public class ModelError { ///
/// 错误码 /// public int code { get; set; } ///
/// 错误描述 /// public string description { get; set; } } } #endregion public static class IO { /// 将 Stream 转成 byte[] public static byte[] StreamToBytes(Stream stream) { byte[] bytes = new byte[stream.Length]; stream.Read(bytes, 0, bytes.Length); // 设置当前流的位置为流的开始 stream.Seek(0, SeekOrigin.Begin); return bytes; } /// 将 byte[] 转成 Stream public static Stream BytesToStream(byte[] bytes) { Stream stream = new MemoryStream(bytes); return stream; } } ///
/// 汉字转换 /// public class ChineseConvert { #region 汉字转拼方法1 ///
汉字转拼音缩写 ///
要转换的汉字字符串 ///
拼音缩写
public static string GetSpellString(string str) { if (IsEnglishCharacter(str)) return str; string tempStr = ""; foreach (char c in str) { if ((int)c >= 33 && (int)c <= 126) { //字母和符号原样保留 tempStr += c.ToString(); } else { //累加拼音声母 tempStr += GetSpellChar(c.ToString()); } } return tempStr; } ///
/// 判断是否字母 /// ///
///
private static bool IsEnglishCharacter(String str) { CharEnumerator ce = str.GetEnumerator(); while (ce.MoveNext()) { char c = ce.Current; if ((c <= 0x007A && c >= 0x0061) == false && (c <= 0x005A && c >= 0x0041) == false) return false; } return true; } ///
/// 判断是否有汉字 /// ///
///
private static bool HaveChineseCode(string testString) { if (Regex.IsMatch(testString, @"[\u4e00-\u9fa5]+")) { return true; } else { return false; } } ///
/// 取单个字符的拼音声母 /// ///
要转换的单个汉字 ///
拼音声母
public static string GetSpellChar(string c) { byte[] array = new byte[2]; array = System.Text.Encoding.Default.GetBytes(c); int i = (short)(array[0] - '\0') * 256 + ((short)(array[1] - '\0')); if (i < 0xB0A1) return "*"; if (i < 0xB0C5) return "a"; if (i < 0xB2C1) return "b"; if (i < 0xB4EE) return "c"; if (i < 0xB6EA) return "d"; if (i < 0xB7A2) return "e"; if (i < 0xB8C1) return "f"; if (i < 0xB9FE) return "g"; if (i < 0xBBF7) return "h"; if (i < 0xBFA6) return "j"; if (i < 0xC0AC) return "k"; if (i < 0xC2E8) return "l"; if (i < 0xC4C3) return "m"; if (i < 0xC5B6) return "n"; if (i < 0xC5BE) return "o"; if (i < 0xC6DA) return "p"; if (i < 0xC8BB) return "q"; if (i < 0xC8F6) return "r"; if (i < 0xCBFA) return "s"; if (i < 0xCDDA) return "t"; if (i < 0xCEF4) return "w"; if (i < 0xD1B9) return "x"; if (i < 0xD4D1) return "y"; if (i < 0xD7FA) return "z"; return "*"; } #endregion #region 汉字转拼方法2 private static Hashtable _Phrase; ///
/// 设置或获取包含列外词组读音的键/值对的组合。 /// public static Hashtable Phrase { get { if (_Phrase == null) { _Phrase = new Hashtable(); _Phrase.Add("圳", "Zhen"); _Phrase.Add("什么", "ShenMe"); _Phrase.Add("晖", "Hui"); _Phrase.Add("孑", "Jie"); } return _Phrase; } set { _Phrase = value; } } #region 定义编码 private static int[] pyvalue = new int[] { -20319, -20317, -20304, -20295, -20292, -20283, -20265, -20257, -20242, -20230, -20051, -20036, -20032, -20026, -20002, -19990, -19986, -19982, -19976, -19805, -19784, -19775, -19774, -19763, -19756, -19751, -19746, -19741, -19739, -19728, -19725, -19715, -19540, -19531, -19525, -19515, -19500, -19484, -19479, -19467, -19289, -19288, -19281, -19275, -19270, -19263, -19261, -19249, -19243, -19242, -19238, -19235, -19227, -19224, -19218, -19212, -19038, -19023, -19018, -19006, -19003, -18996, -18977, -18961, -18952, -18783, -18774, -18773, -18763, -18756, -18741, -18735, -18731, -18722, -18710, -18697, -18696, -18526, -18518, -18501, -18490, -18478, -18463, -18448, -18447, -18446, -18239, -18237, -18231, -18220, -18211, -18201, -18184, -18183, -18181, -18012, -17997, -17988, -17970, -17964, -17961, -17950, -17947, -17931, -17928, -17922, -17759, -17752, -17733, -17730, -17721, -17703, -17701, -17697, -17692, -17683, -17676, -17496, -17487, -17482, -17468, -17454, -17433, -17427, -17417, -17202, -17185, -16983, -16970, -16942, -16915, -16733, -16708, -16706, -16689, -16664, -16657, -16647, -16474, -16470, -16465, -16459, -16452, -16448, -16433, -16429, -16427, -16423, -16419, -16412, -16407, -16403, -16401, -16393, -16220, -16216, -16212, -16205, -16202, -16187, -16180, -16171, -16169, -16158, -16155, -15959, -15958, -15944, -15933, -15920, -15915, -15903, -15889, -15878, -15707, -15701, -15681, -15667, -15661, -15659, -15652, -15640, -15631, -15625, -15454, -15448, -15436, -15435, -15419, -15416, -15408, -15394, -15385, -15377, -15375, -15369, -15363, -15362, -15183, -15180, -15165, -15158, -15153, -15150, -15149, -15144, -15143, -15141, -15140, -15139, -15128, -15121, -15119, -15117, -15110, -15109, -14941, -14937, -14933, -14930, -14929, -14928, -14926, -14922, -14921, -14914, -14908, -14902, -14894, -14889, -14882, -14873, -14871, -14857, -14678, -14674, -14670, -14668, -14663, -14654, -14645, -14630, -14594, -14429, -14407, -14399, -14384, -14379, -14368, -14355, -14353, -14345, -14170, -14159, -14151, -14149, -14145, -14140, -14137, -14135, -14125, -14123, -14122, -14112, -14109, -14099, -14097, -14094, -14092, -14090, -14087, -14083, -13917, -13914, -13910, -13907, -13906, -13905, -13896, -13894, -13878, -13870, -13859, -13847, -13831, -13658, -13611, -13601, -13406, -13404, -13400, -13398, -13395, -13391, -13387, -13383, -13367, -13359, -13356, -13343, -13340, -13329, -13326, -13318, -13147, -13138, -13120, -13107, -13096, -13095, -13091, -13076, -13068, -13063, -13060, -12888, -12875, -12871, -12860, -12858, -12852, -12849, -12838, -12831, -12829, -12812, -12802, -12607, -12597, -12594, -12585, -12556, -12359, -12346, -12320, -12300, -12120, -12099, -12089, -12074, -12067, -12058, -12039, -11867, -11861, -11847, -11831, -11798, -11781, -11604, -11589, -11536, -11358, -11340, -11339, -11324, -11303, -11097, -11077, -11067, -11055, -11052, -11045, -11041, -11038, -11024, -11020, -11019, -11018, -11014, -10838, -10832, -10815, -10800, -10790, -10780, -10764, -10587, -10544, -10533, -10519, -10331, -10329, -10328, -10322, -10315, -10309, -10307, -10296, -10281, -10274, -10270, -10262, -10260, -10256, -10254 }; private static string[] pystr = new string[] { "a", "ai", "an", "ang", "ao", "ba", "bai", "ban", "bang", "bao", "bei", "ben", "beng", "bi", "bian", "biao", "bie", "bin", "bing", "bo", "bu", "ca", "cai", "can", "cang", "cao", "ce", "ceng", "cha", "chai", "chan" , "chang", "chao", "che", "chen", "cheng", "chi", "chong", "chou", "chu", "chuai", "chuan", "chuang", "chui", "chun", "chuo", "ci", "cong" , "cou", "cu", "cuan", "cui", "cun", "cuo", "da", "dai", "dan", "dang", "dao", "de", "deng", "di", "dian", "diao", "die", "ding", "diu", "dong", "dou", "du", "duan", "dui", "dun", "duo", "e", "en", "er", "fa", "fan", "fang", "fei", "fen", "feng", "fo", "fou", "fu", "ga" , "gai", "gan", "gang", "gao", "ge", "gei", "gen", "geng", "gong", "gou", "gu", "gua", "guai", "guan", "guang", "gui", "gun", "guo", "ha", "hai", "han", "hang", "hao", "he", "hei", "hen", "heng", "hong", "hou", "hu", "hua", "huai", "huan", "huang", "hui", "hun", "huo", "ji", "jia", "jian", "jiang", "jiao", "jie", "jin", "jing", "jiong", "jiu", "ju", "juan", "jue", "jun", "ka", "kai", "kan", "kang", "kao", "ke", "ken", "keng", "kong", "kou", "ku", "kua", "kuai", "kuan", "kuang", "kui", "kun", "kuo", "la", "lai", "lan", "lang", "lao", "le", "lei", "leng", "li", "lia", "lian", "liang", "liao", "lie", "lin", "ling", "liu", "long", "lou", "lu", "lv", "luan", "lue", "lun", "luo", "ma", "mai", "man", "mang", "mao", "me", "mei", "men", "meng", "mi", "mian", "miao", "mie", "min", "ming", "miu", "mo", "mou", "mu", "na", "nai", "nan", "nang", "nao", "ne", "nei", "nen", "neng", "ni", "nian", "niang", "niao", "nie", "nin", "ning", "niu", "nong", "nu", "nv", "nuan", "nue", "nuo", "o", "ou", "pa", "pai", "pan", "pang", "pao", "pei", "pen", "peng", "pi", "pian", "piao", "pie", "pin", "ping", "po", "pu", "qi", "qia", "qian", "qiang", "qiao", "qie", "qin", "qing", "qiong", "qiu", "qu", "quan", "que", "qun", "ran", "rang", "rao", "re", "ren", "reng", "ri", "rong", "rou", "ru", "ruan", "rui", "run", "ruo", "sa", "sai", "san", "sang", "sao", "se", "sen", "seng", "sha", "shai", "shan", "shang", "shao", "she", "shen", "sheng", "shi", "shou", "shu", "shua", "shuai", "shuan", "shuang", "shui", "shun", "shuo", "si", "song", "sou", "su", "suan", "sui", "sun", "suo", "ta", "tai", "tan", "tang", "tao", "te", "teng", "ti", "tian", "tiao", "tie", "ting", "tong", "tou", "tu", "tuan", "tui", "tun", "tuo", "wa", "wai", "wan", "wang", "wei", "wen", "weng", "wo", "wu", "xi", "xia", "xian", "xiang", "xiao", "xie", "xin", "xing", "xiong", "xiu", "xu", "xuan", "xue", "xun", "ya", "yan", "yang", "yao", "ye", "yi", "yin", "ying", "yo", "yong", "you", "yu", "yuan", "yue", "yun", "za", "zai", "zan", "zang", "zao", "ze", "zei", "zen", "zeng", "zha", "zhai" , "zhan", "zhang", "zhao", "zhe", "zhen", "zheng", "zhi", "zhong", "zhou", "zhu", "zhua", "zhuai", "zhuan", "zhuang", "zhui", "zhun", "zhuo", "zi", "zong", "zou", "zu", "zuan", "zui", "zun", "zuo" }; #endregion #region 获取汉字拼音 ///
/// 获取汉字拼音 /// ///
汉字字符串 ///
拼音
public static string GetSpellByChinese(string _chineseString) { string strRet = string.Empty; // 例外词组 foreach (DictionaryEntry de in Phrase) { _chineseString = _chineseString.Replace(de.Key.ToString(), de.Value.ToString()); } char[] ArrChar = _chineseString.ToCharArray(); foreach (char c in ArrChar) { strRet += GetSingleSpellByChinese(c.ToString()); } return strRet; } #endregion #region 获取汉字拼音首字母 ///
/// 获取汉字拼音首字母 /// ///
指定汉字 ///
拼音首字母
public static string GetHeadSpellByChinese(string _chineseString) { string strRet = string.Empty; char[] ArrChar = _chineseString.ToCharArray(); foreach (char c in ArrChar) { strRet += GetHeadSingleSpellByChinese(c.ToString()); } return strRet; } #endregion #region 获取单个汉字拼音 ///
/// 获取单个汉字拼音 /// ///
单个汉字 ///
拼音
public static string GetSingleSpellByChinese(string _singleChineseString) { byte[] array = Encoding.Default.GetBytes(_singleChineseString); int iAsc; string strRtn = string.Empty; try { iAsc = (short)(array[0]) * 256 + (short)(array[1]) - 65536; } catch { iAsc = 1; } if (iAsc > 0 && iAsc < 160) return _singleChineseString; for (int i = (pyvalue.Length - 1); i >= 0; i--) { if (pyvalue[i] <= iAsc) { strRtn = pystr[i]; break; } } //将首字母转为大写 if (strRtn.Length > 1) { strRtn = strRtn.Substring(0, 1).ToUpper() + strRtn.Substring(1); } return strRtn; } #endregion #region 获取单个汉字的首字母 ///
/// 获取单个汉字的首字母 /// ///
public static string GetHeadSingleSpellByChinese(string _singleChineseString) { // 例外词组 foreach (DictionaryEntry de in Phrase) { _singleChineseString = _singleChineseString.Replace(de.Key.ToString(), de.Value.ToString()); } string text = ""; try { text = GetSingleSpellByChinese(_singleChineseString).Substring(0, 1); } catch { } return text; } #endregion #region 获取汉字拼音(第一个汉字只有首字母) ///
/// 获取汉字拼音(第一个汉字只有首字母) /// ///
///
public static string GetAbSpellByChinese(string _chineseString) { string strRet = string.Empty; // 例外词组 foreach (DictionaryEntry de in Phrase) { _chineseString = _chineseString.Replace(de.Key.ToString(), de.Value.ToString()); } char[] ArrChar = _chineseString.ToCharArray(); for (int i = 0; i < ArrChar.Length; i++) { if (i == 0) { strRet += GetHeadSingleSpellByChinese(ArrChar[i].ToString()); } else { strRet += GetSingleSpellByChinese(ArrChar[i].ToString()); } } return strRet; } #endregion ///
/// 获取5种汉字转拼音 /// ///
///
public static string GetAllSpellByChinese(string str) { string str_temp = ""; str_temp = GetSpellByChinese(str.Trim()); str_temp += "," + GetHeadSpellByChinese(str.Trim()); str_temp += "," + GetSingleSpellByChinese(str.Trim()); str_temp += "," + GetHeadSingleSpellByChinese(str.Trim()); str_temp += "," + GetAbSpellByChinese(str.Trim()); return str_temp; } ///
/// 获取5种汉字转拼音 /// ///
///
public static string GetAllSpellByChinese(string str, string fg) { string str_temp = ""; str_temp = GetSpellByChinese(str.Trim()); str_temp += fg + GetHeadSpellByChinese(str.Trim()); str_temp += fg + GetSingleSpellByChinese(str.Trim()); str_temp += fg + GetHeadSingleSpellByChinese(str.Trim()); str_temp += fg + GetAbSpellByChinese(str.Trim()); return str_temp; } #endregion } }}

 

转载于:https://www.cnblogs.com/OleRookie/p/8390752.html

你可能感兴趣的文章
C语言--第0次作业
查看>>
POJ1200(hash)
查看>>
有参装饰器实现登录用户文件验证和验证失败锁定
查看>>
2018-02-27 "Literate Programming"一书摘记之一
查看>>
L2-003. 月饼
查看>>
jsp html5 video实现在线视频播放源码,支持IE6,7,8,10,11,谷歌,火狐等浏览器
查看>>
codeforces 8VC Venture Cup 2016 - Elimination Round C. Lieges of Legendre
查看>>
Eclipse断点调试(上)
查看>>
Spring的aop操作
查看>>
平差方法
查看>>
关于有序guid 的使用
查看>>
arcgis 画图工具
查看>>
[Leetcode]leetcode1-10题随记
查看>>
HDU 4162 Shape Number
查看>>
HDU 5211 Mutiple 水题
查看>>
linux中ctrl+z、ctrl+d和ctrl+c的区别
查看>>
mysql数据库的简单操作
查看>>
走过2013,走进2014
查看>>
修改tomcatlog输出等级
查看>>
数据结构 堆栈
查看>>