C# 拼音通用类

因为项目需求,查找资料并编写了这个拼音通用类。在博客园分享:)

其中的多音字首拼,感觉还是非常实用的。可识别中文、英文和符号

  1 using System;
  2 using System.Collections.Generic;
  3 using System.Collections.ObjectModel;
  4 using System.Linq;
  5 using System.Text;
  6 using Microsoft.International.Converters.PinYinConverter;
  7
  8 namespace MyConsoleApp
  9 {
 10     public sealed class PinYin
 11     {
 12         private PinYin() { }
 13
 14         /// <summary>
 15         /// 获取首拼或全拼。大写
 16         /// </summary>
 17         /// <param name="chineseString"></param>
 18         /// <param name="isFull">true为全拼,false为首拼</param>
 19         /// <returns></returns>
 20         public static string GetPY(string chineseString, bool isFull)
 21         {
 22             StringBuilder sb = new StringBuilder(50);
 23             foreach (var item in chineseString.ToCharArray())
 24             {
 25                 if (!ChineseChar.IsValidChar(item))
 26                 {
 27                     sb.Append(item);
 28                 }
 29                 else
 30                 {
 31                     System.Collections.ObjectModel.ReadOnlyCollection<string> py = new ChineseChar(item).Pinyins;
 32                     if (py.Count > 0 && py[0].Length > 0)
 33                     {
 34                         if (isFull)
 35                             sb.Append(py[0].Substring(0, py[0].Length - 1));
 36                         else
 37                             sb.Append(py[0][0]);
 38                     }
 39                 }
 40             }
 41             return sb.ToString();
 42         }
 43
 44         /// <summary>
 45         /// 获取首拼和全拼
 46         /// </summary>
 47         /// <param name="chineseString"></param>
 48         /// <param name="pyStr"></param>
 49         /// <param name="pyFullStr"></param>
 50         public static void GetPY(string chineseString, out string pyStr, out string pyFullStr)
 51         {
 52             StringBuilder sb = new StringBuilder(50);
 53             StringBuilder sbFull = new StringBuilder(50);
 54             foreach (var item in chineseString.ToCharArray())
 55             {
 56                 if (!ChineseChar.IsValidChar(item))
 57                 {
 58                     sb.Append(item);
 59                     sbFull.Append(item);
 60                 }
 61                 else
 62                 {
 63                     System.Collections.ObjectModel.ReadOnlyCollection<string> py = new ChineseChar(item).Pinyins;
 64                     if (py.Count > 0 && py[0].Length > 0)
 65                     {
 66                         sbFull.Append(py[0].Substring(0, py[0].Length - 1));
 67                         sb.Append(py[0][0]);
 68                     }
 69                 }
 70             }
 71
 72             pyStr = sb.ToString();
 73             pyFullStr = sbFull.ToString();
 74         }
 75
 76         /// <summary>
 77         /// 获取首拼(多音字"|"分隔)和全拼
 78         /// </summary>
 79         /// <param name="chineseString"></param>
 80         /// <param name="pyStr"></param>
 81         /// <param name="pyFullStr"></param>
 82         public static void GetHomoPhonePY(string chineseString, out string pyStr, out string pyFullStr)
 83         {
 84             StringBuilder sb = new StringBuilder(50);
 85             StringBuilder sbFull = new StringBuilder(50);
 86
 87             char[] chineseCharArray = chineseString.ToCharArray();
 88             Dictionary<int, List<string>> dic = new Dictionary<int, List<string>>();
 89
 90             for (int i = 0; i < chineseCharArray.Length; i++)
 91             {
 92                 char item = chineseCharArray[i];
 93                 if (!ChineseChar.IsValidChar(item))
 94                 {
 95                     sb.Append(item);
 96                     sbFull.Append(item);
 97                 }
 98                 else
 99                 {
100                     ChineseChar chinaChar = new ChineseChar(item);
101                     ReadOnlyCollection<string> py = chinaChar.Pinyins;
102                     if (py.Count > 0 && py[0].Length > 0)
103                     {
104                         sbFull.Append(py[0].Substring(0, py[0].Length - 1));
105                         dic.Add(i, py.Where(p => !string.IsNullOrEmpty(p)).Select(p => p[0].ToString()).Distinct().ToList());
106                     }
107                 }
108             }
109
110             OutPutHomoPhone(dic, dic.Keys.Count, 0, "", ref sb);
111
112             pyStr = sb.ToString();
113             pyFullStr = sbFull.ToString();
114         }
115
116         /// <summary>
117         /// 获取多音字首拼(多音字"|"分隔)
118         /// 西门子SIEMENS商标->XMZSIEMENSSB
119         /// </summary>
120         /// <param name="chineseString"></param>
121         /// <returns></returns>
122         public static string GetHomoPhonePY(string chineseString)
123         {
124             StringBuilder sb = new StringBuilder(50);
125
126             char[] chineseCharArray = chineseString.ToCharArray();
127             Dictionary<int, List<string>> dic = new Dictionary<int, List<string>>();
128
129             for (int i = 0; i < chineseCharArray.Length; i++)
130             {
131                 char item = chineseCharArray[i];
132                 if (!ChineseChar.IsValidChar(item))
133                 {
134                     dic.Add(i, new List<string> { item.ToString() });
135                 }
136                 else
137                 {
138                     ChineseChar chinaChar = new ChineseChar(item);
139                     ReadOnlyCollection<string> py = chinaChar.Pinyins;
140                     if (py.Count > 0 && py[0].Length > 0)
141                     {
142                         dic.Add(i, py.Where(p => !string.IsNullOrEmpty(p)).Select(p => p[0].ToString()).Distinct().ToList());
143                     }
144                 }
145             }
146
147             OutPutHomoPhone(dic, dic.Keys.Count, 0, "", ref sb);
148
149             return sb.ToString();
150         }
151
152         /// <summary>
153         /// 递归出多音字的首拼
154         /// </summary>
155         /// <param name="dic">多音字字典</param>
156         /// <param name="len">字数</param>
157         /// <param name="key">字典下标</param>
158         /// <param name="parentValue">递归的首拼</param>
159         /// <param name="sb">结果对象</param>
160         private static void OutPutHomoPhone(
161             Dictionary<int, List<string>> dic,
162             int len,
163             int key,
164             string parentValue,
165             ref StringBuilder sb)
166         {
167             if (dic.Keys.Contains(key))
168             {
169                 foreach (string x in dic[key])
170                 {
171                     if (dic.Keys.Count - 1 >= key)
172                     {
173                         string outString = string.Format("{0}{1}", parentValue, x);
174                         if (outString.Length == len)
175                         {
176                             sb.AppendFormat("{0}|", outString);
177                         }
178                         OutPutHomoPhone(dic, len, key + 1, outString, ref sb);
179                     }
180                 }
181             }
182         }
183
184     }
185 }

C# 拼音通用类

时间: 2024-11-02 13:47:40

C# 拼音通用类的相关文章

C#---数据库访问通用类、Access数据库操作类、mysql类 .[转]

原文链接 //C# 数据库访问通用类 (ADO.NET)using System;using System.Collections.Generic;using System.Text;using System.Data;using System.Data.SqlClient;using System.Configuration; namespace XXX{    /// <summary>    /// 针对SQL Server数据库操作的通用类           /// </sum

jQuery Ajax封装通用类 (linjq)

jQuery Ajax封装通用类 (linjq) $(function(){ /** * ajax封装 * url 发送请求的地址 * data 发送到服务器的数据,数组存储,如:{"date": new Date().getTime(), "state": 1} * async 默认值: true.默认设置下,所有请求均为异步请求.如果需要发送同步请求,请将此选项设置为 false. * 注意,同步请求将锁住浏览器,用户其它操作必须等待请求完成才可以执行. * t

poi导出excel通用类

一.关键的通用类public class PoiExportUtils {    private static HSSFWorkbook workBook; public PoiExportUtils(){        workBook = new HSSFWorkbook();    }        /**     * 创建sheet     * @param sheetName     * @param workBook     * @return     */    public st

PHP curl get post通用类

<?php /** * @author:xiaojiang * curl 通用方法 ..get /post 传送数据 */ class process{ const GET = 0; const POST = 1; public $url; public $ch = null; private $type = 1; public function __construct( $url , $type = self::POST){ $this->url = $url; $this->ch =

DataTable转换为List&lt;Model&gt;的通用类

在开发中,把查询结果以DataTable返回很方便,但是在检索数据时又很麻烦,没有模型类型检索方便. 所以很多人都是按照以下方式做的: // 获得查询结果DataTable dt = DbHelper.ExecuteDataTable(...);// 把DataTable转换为IList<UserInfo>IList<UserInfo> users = ConvertToUserInfo(dt); 问题:如果此系统有几十上百个模型,那不是每个模型中都要写个把DataTable转换为

MVC AJAX导出Excel通用类

通用类: public enum DataTypeEnum { Int = 0, Float = 1, Double = 2, String = 3, DateTime = 4, Date = 5 } public class ExportFieldInfo { /// <summary> /// 字段名,用于反射获取值 /// </summary> public string FieldName { get; set; } /// <summary> /// 中文名,

Memcached通用类(基于enyim.com Memcached Client)

一.如果用官方提供的方法,在web.config里面配置好了各个参数和服务器IP.如下图: <?xml version="1.0"?> <configuration> <configSections> <sectionGroup name="enyim.com"> <section name="memcached" type="Enyim.Caching.Configuration.

ASP.NET文件操作通用类

1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 6 using System.IO; 7 using System.Web; 8 using System.Web.UI; 9 using System.Web.UI.WebControls; 10 11 12 public class WebFileHelper 13 { 14 15 FileInfo f

[.net 面向对象程序设计进阶] (11) 序列化(Serialization)(三) 通过接口IXmlSerializable实现XML序列化及XML通用类

[.net 面向对象程序设计进阶] (11) 序列化(Serialization)(三) 通过接口IXmlSerializable实现XML序列化及XML通用类 本节导读:本节主要介绍通过序列化接口IXmlSerializable实现XML序列化和反序列化,整理了XML基础操作及序列化的通用类(包括XML及节点的基础读写操作,XML到DataSet\DataTable互转换操作,XML序列化及反序列化通用方法等). 读前必备: A.类和类的实例 [.net 面向对象编程基础]  (9) 类和类的