当前位置:网站首页>QT 如何计算中英文字符串的长度
QT 如何计算中英文字符串的长度
2022-07-29 18:19:00 【hellokandy】
日常开发中,可能都会用到统计字符串长度,如果是英文和数字,一般情况计算出来的长度是正确的。但是,遇到中英文混合的情况,如果还是用之前的统计方式,得到的结果往往是不准确的!
在QT帮助文档中,我们可以找到关于QString用来计算字符个数的函数:length()
int QString::length() const
Returns the number of characters in this string. Equivalent to size().
如果直接使用 length() 来计算字符串长度,在遇到中英文混合的字符串时,就会抓瞎!那么准确计算中英文字符串长度的代码是什么样的呢?
正确计算中英文字符串长度的代码
#include <QtCore/QCoreApplication>
#include <QDebug>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
int length = 0;
QString qstrEN = "hello,world!";
length = qstrEN.length();//12
qDebug() << "qstrEN.length()=" << length;
QString qstrZH = "好好学习,天天向上!";
length = qstrZH.length();//16?
qDebug() << "qstrZH.length()=" << length;
qstrZH = QString::fromLocal8Bit("好好学习,天天向上!");
length = qstrZH.toLocal8Bit().length();//20,OK!
qDebug() << "qstrZH.length()=" << length;
QString qstrMisc = QString::fromLocal8Bit("Good Good Study!天天向上!");
length = qstrMisc.length();//21
qDebug() << "qstrMisc.length()=" << length;
length = qstrMisc.toLocal8Bit().length();//26,OK!
qDebug() << "qstrMisc.length()=" << length;
//字符串截取
QByteArray bytestr = qstrMisc.toLocal8Bit().left(20);
qDebug() << "bytestr=" << bytestr;//"Good Good Study!\xCC\xEC\xCC\xEC"
QString localstr = QString::fromLocal8Bit(bytestr);
qDebug() << "localstr=" << localstr;//"Good Good Study!天天"
return 0;
}
输出结果:
qstrEN.length()= 12
qstrZH.length()= 16
qstrZH.length()= 20
qstrMisc.length()= 21
qstrMisc.length()= 26
bytestr= "Good Good Study!\xCC\xEC\xCC\xEC"
localstr= "Good Good Study!天天"
可以看到,在遇到中文或者中英文混合的字符串时,我们必须先通过 toLocal8Bit() 转为本地操作系统设置的字符集编码,然后再使用 length() 计算,才能得到正确的结果!
边栏推荐
猜你喜欢
随机推荐
160亿美元!传微软计划收购全球最大语音识别公司
KubeMeet 报名 | 「边缘原生」线上技术沙龙完整议程公布!
十大企业数据安全优秀实践
北汇信息继续扩大V2X测试服务,扎根重庆,服务全国
要卖课、要带货,知识付费系统帮你一步搞定!
数字化来势汹汹,低代码起势,JNPF助力企业定制专属BIM
pkg_resources.DistributionNotFound: The 'pip==1.4' distribution was not found and is required
滚动条样式
公司无线规划设计及实施SOP
One's deceased father grind English vocabulary training camp Day 】 16 - bankrupt, remain, regulate, the construct and reflect
无人驾驶与人工驾驶的对比,人工驾驶的优缺点
2022开放原子全球开源峰会OpenAnolis分论坛圆满落幕
商业智能BI为什么能在数字化时代成为企业的基础建设
如何灵活管理权限,保障团队数据安全?|2分钟了解 ONES
碎片化时间真的适合学习吗?
Setting right:0 after sticky positioning does not take effect
500强企业如何提升研发效能?来看看行业专家怎么说
数据监控体系是什么?该怎么搭建?
平行坐标图:高维数据可视化必备图形
疫情之下,逆势成长的平板市场,究竟会不会是昙花一现?









