dotnet中文字符工具类

支持繁体简体互换。

 1 using System;
 2 using System.Collections.Generic;
 3 using System.IO;
 4 using System.Linq;
 5 using System.Runtime.InteropServices;
 6 using System.Threading.Tasks;
 7 
 8 namespace DLMApi.Utils
 9 {
10     /// <summary>
11     /// 中文字符工具类
12     /// </summary>
13     public  class ChineseStringUtility
14     {
15         private const int LOCALE_SYSTEM_DEFAULT = 0x0800;
16         private const int LCMAP_SIMPLIFIED_CHINESE = 0x02000000;
17         private const int LCMAP_TRADITIONAL_CHINESE = 0x04000000;
18 
19         [DllImport("kernel32", CharSet = CharSet.Auto, SetLastError = true)]
20         private static extern int LCMapString(int Locale, int dwMapFlags, string lpSrcStr, int cchSrc, [Out] string lpDestStr, int cchDest);
21 
22         /// <summary>
23         /// 将字符转换成简体中文
24         /// </summary>
25         /// <param name="source">输入要转换的字符串</param>
26         /// <returns>转换完成后的字符串</returns>
27         public static string ToSimplified(string source)
28         {
29             String target = new String(' ', source.Length);
30             int ret = LCMapString(LOCALE_SYSTEM_DEFAULT, LCMAP_SIMPLIFIED_CHINESE, source, source.Length, target, source.Length);
31             return target;
32         }
33 
34         /// <summary>
35         /// 将字符转换为繁体中文
36         /// </summary>
37         /// <param name="source">输入要转换的字符串</param>
38         /// <returns>转换完成后的字符串</returns>
39         public static string ToTraditional(string source)
40         {
41             String target = new String(' ', source.Length);
42             int ret = LCMapString(LOCALE_SYSTEM_DEFAULT, LCMAP_TRADITIONAL_CHINESE, source, source.Length, target, source.Length);
43             return target;
44         }
45 
46         // <summary>
47         /// 获取两个字符串的相似度
48         /// </summary>
49         /// <param name=”sourceString”>第一个字符串</param>
50         /// <param name=”str”>第二个字符串</param>
51         public static int GetSimilarityWith(string sourceString, string str)
52         {
53             char[] ss = sourceString.ToCharArray();
54             char[] st = str.ToCharArray();
55 
56             //获取交集数量
57             int q = ss.Intersect(st).Count();
58             return q;
59         }
60 
61     }
62 }

 

posted @ 2019-08-15 17:15  ccsoft  阅读(202)  评论(0编辑  收藏  举报