Recently, the requirement of using Chinese characters to pinyin in the project is realized by NPinyin, but in the process of using it, there is a situation that does not meet the expectations.
Let's take a look at normal use first:
string str = NPinyin.Pinyin.GetPinyin("小黄本黄");
Console.WriteLine(str);
The output is
xiao huang ben huang
Obviously, this is expected, but if we don't know whether the current string is Chinese or Pinyin before calling this conversion method, do we expect that the Pinyin part will not be changed? But not actually:
string str = NPinyin.Pinyin.GetPinyin("xiao huang ben huang");
Console.WriteLine(str);
The output is
xiaohuangbenhuang
It also converts each English character, resulting in an extra space after each character.
If we make the following adjustments, we can return our expected results
public static string GetPinyin(string str)
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < str.Length; i++)
{
if (str[i] > 127)
{
string pinyin = Pinyin.GetPinyin(str[i]);
sb.Append(pinyin);
// 如果是最后一位,就不用追加空格
if (i == str.Length - 1)
continue;
// 如果不是最后一位,但下一位是符号,也不用追加空格
if (char.IsPunctuation(str[i+1]))
continue;
sb.Append(" ");
continue;
}
sb.Append(str[i]);
}
return sb.ToString();
}
let's test
string str = GetPinyin("Xiao Huang 本黄。");
Console.WriteLine(str);
The output is
Xiao Huang ben huang.
Just sauce!
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。