2014年3月5日星期三 北京海淀五路居 晴
今天找了一本简单的C#教材,补一补脆弱的根基。1.string,被我忽视的’\0’
在实现字母和ASCII码转化的时候,忘记了末端的’\0’,问题不小。
// Encoding.Unicode.GetBytes(tbFromAlpha.Text)得到的是一个包含两个元素的字节数组
// byte[0]=97,byte[1]=0,直接将数组转换成字符串,结果相差甚远
tbToASCII.Text = Encoding.Unicode.GetBytes(tbFromAlpha.Text).ToString();
1) 安装插件
Microsoft Visual Studio International Pack 1.0 SR1
2)添加引用
安装目录下的ChnCharInfo.dll
using Microsoft.International.Converters.PinYinConverter;
3) 进行转换
//使用正则表达式,将汉字过滤出来
Regex reg = new Regex("^[\u4e00-\u9ffa5]$");
//将汉字转化为字符数组,用于遍历
char[] wordChars = str.ToCharArray();
foreach (char ch in wordChars) {
if(reg.IsMatch(ch.ToString())) { //是否为汉字
ChineseChar chineseCh = new ChineseChar(ch); //安装的插件终于开始使用了
string tempPinYin = chineseCh.Pinyins[0].ToString();
//获得汉字的拼音
string lowerPinYin = tempPinYin.ToLower().Substring(1, tempPinYin.Length - 1);
tempPinYin = tempPinYin[0].ToString() + lowerPinYin; //让首字母大写
pystr += tempPinYin.Substring(0, tempPinYin.Length - 1); //去掉拼音后面的数字,返回的值总是全拼+一个数字
}
else { //不是汉字,直接拼接
pystr += ch;
}
}