本文实例为大家分享了ASP.NET Core实现汉字转拼音的具体代码,供大家参考,具体内容如下
一、NuGet包
拼音:Install-Package PinYinConverterCore
简体-繁体互转:Install-Package TraditionalChineseToSimplifiedConverter
二、C#代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
|
class Program
{
static void Main( string [] args)
{
string Name= "刘大大" ;
Console.WriteLine($ "{Name}\n全拼:{GetPinyin(Name)},\n首拼:{GetFirstPinyin(Name)},\n繁体字:{GetTraditional(Name)},\n简体字:{GetSimplified(GetTraditional(Name))}" );
Console.ReadKey();
}
/// <summary>
/// 汉字转化为拼音
/// </summary>
/// <param name="str">汉字</param>
/// <returns>全拼</returns>
public static string GetPinyin( string str)
{
string r = string .Empty;
foreach ( char obj in str)
{
try
{
ChineseChar chineseChar = new ChineseChar(obj);
string t = chineseChar.Pinyins[0].ToString();
r += t.Substring(0, t.Length - 1);
}
catch
{
r += obj.ToString();
}
}
return r;
}
/// <summary>
/// 汉字转化为拼音首字母
/// </summary>
/// <param name="str">汉字</param>
/// <returns>首字母</returns>
public static string GetFirstPinyin( string str)
{
string r = string .Empty;
foreach ( char obj in str)
{
try
{
ChineseChar chineseChar = new ChineseChar(obj);
string t = chineseChar.Pinyins[0].ToString();
r += t.Substring(0, 1);
}
catch
{
r += obj.ToString();
}
}
return r;
}
// <summary>
/// 简体转换为繁体
/// </summary>
/// <param name="str">简体字</param>
/// <returns>繁体字</returns>
public static string GetTraditional( string str)
{
string r = string .Empty;
r = ChineseConverter.Convert(str, ChineseConversionDirection.SimplifiedToTraditional);
return r;
}
/// <summary>
/// 繁体转换为简体
/// </summary>
/// <param name="str">繁体字</param>
/// <returns>简体字</returns>
public static string GetSimplified( string str)
{
string r = string .Empty;
r = ChineseConverter.Convert(str, ChineseConversionDirection.TraditionalToSimplified);
return r;
}
#endregion
}
}
|
运行结果
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。
原文链接:https://www.cnblogs.com/lwc1st/archive/2018/05/16/9045382.html