日常开发中,可能都会用到统计字符串长度,如果是英文和数字,一般情况计算出来的长度是正确的。但是,遇到中英文混合的情况,如果还是用之前的统计方式,得到的结果往往是不准确的!
用户心里预期
我们在一些网站上填写信息时,一般都会有字符个数的提示,对于用户而言,只要输入的都算字符,别管中文字符英文字符占多少个字节,那是你们程序员的事情!那么我们先共识一下用户的心里预期:
abc123,这个是6个字符
我是中国人,这也是6个字符
abc123我是中国人,这是12个字符
在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.length();//10,OK!
qDebug() << "qstrZH.length()=" << length;
QString qstrMisc = QString::fromLocal8Bit("Good Good Study!天天向上!");
length = qstrMisc.toLocal8Bit().length();//26
qDebug() << "qstrMisc.length()=" << length;
length = qstrMisc.length();//21,OK!
qDebug() << "qstrMisc.length()=" << length;
//字符串截取
QByteArray bytestr = qstrMisc.toLocal8Bit().left(18);
qDebug() << "bytestr=" << bytestr;//"Good Good Study!\xCC\xEC"
QString localstr = QString::fromLocal8Bit(bytestr);
qDebug() << "localstr=" << localstr;//"Good Good Study!天"
//okey!
QString strOkey = qstrMisc.left(18);
qDebug() << "strOkey=" << strOkey;//"Good Good Study!天天"
return a.exec();
}
输出结果:
qstrEN.length()= 12
qstrZH.length()= 16
qstrZH.length()= 10
qstrMisc.length()= 26
qstrMisc.length()= 21
bytestr= "Good Good Study!\xCC\xEC"
localstr= "Good Good Study!天"
strOkey= "Good Good Study!天天"
可以看到,在遇到中文或者中英文混合的字符串时,我们必须先通过 toLocal8Bit() 转为本地操作系统设置的字符集编码,然后再使用 length() 计算,才能得到正确的结果!