Qt中UTF-8转Unicode

来源:互联网 发布:江苏高考知乎 编辑:程序博客网 时间:2024/06/04 20:43
#include <QtCore/QCoreApplication>#include <QDebug>#include <iostream>#include <QTextCodec>int main(int argc, char *argv[]){    QCoreApplication a(argc, argv);   // const std::string str = "汉字";    const QString str = "汉字";    std::cout << str.length() << std::endl;    QTextCodec *codec = QTextCodec::codecForName("UTF-8");    QString unicode_str = codec->toUnicode(str.toLatin1().data());    for(int i = 0;i <unicode_str.length();++i) {        qDebug() << QString::number(unicode_str[i].unicode(),16);    }        return a.exec();}

注意点了

1.

QTextCodec *codec = QTextCodec::codecForName("UTF-8");
这个的选择要和你系统的编码相对应,我的系统编码方案是UTF-8,所以长度为6,因为一个UTF-8的字符使用3个字节来表示,不然就会出错。还有就是对于QString
使用
str.toLatin1().data()
如果是std::string直接使用str.data()就可以了