需求功能
输入一句汉语,转换成拼音全拼、简拼、每个字首字母及整句话首字母;
封装成单独的类,供后续使用方便;
运行效果
系统实现
汉语转拼音:
//汉语转拼音
QString CNLHelper::CNToPY(const QString &cnstr)
{
QStringList list;
for (int i = 0; i < cnstr.length(); ++i) {
int unicode = QString::number(cnstr.at(i).unicode(), 10).toInt();
if (unicode >= 0x4E00 && unicode <= 0x9FA5) {
//这里的listPY就是按照UNICODE每个中文对应的拼音数组
list.append(listPY.at(unicode - 0x4E00));
} else {
list.append(cnstr.at(i));
}
}
return list.join(" ");
}
转简拼:
//汉语转所有字首字母
QString CNLHelper::CNToEL(const QString &cnstr)
{
QString strChineseFirstPY = listJP.join("");
if(cnstr.length() == 0) {
return cnstr;
}
QString str;
int index = 0;
for(int i = 0; i < cnstr.length(); i++) {
//若是字母或数字则直接输出
ushort vChar = cnstr.at(i).unicode() ;
if((vChar >= 'a' && vChar <= 'z' ) || (vChar >= 'A' && vChar <= 'Z')) {
str.append(cnstr.at(i).toUpper());
}
if((vChar >= '0' && vChar <= '9')) {
str.append(cnstr.at(i));
} else {
index = (int)vChar - 19968;
if(index >= 0 && index < strChineseFirstPY.length()) {
str.append(strChineseFirstPY.at(index));
}
}
}
return str;
}
汉语转第一个汉字首字母:
//汉语转第一个汉字首字母
QString CNLHelper::CNToFL(const QString &cnstr)
{
return CNToEL(cnstr.mid(0,1));//取第一个汉字 并计算首字母
}
加入资源文件 “ cnl.txt ”:
项目源码
Github:lizhifun / QtCNLetter
Github 汉字拼音数据项目:mozillazg/pinyin-data
开发环境
Author:Lizhifun
OS:Windows 10 家庭中文版
Compiler:Microsoft Visual C++ Compiler 15.9.28307.1259(amd64)
Kit:Desktop Qt 5.14.2 MSVC2017 64bit
Qt Creator:4.11.1
参考文章:http://www.qtcn.org/bbs/read-htm-tid-65502.html