Qt程序设计之Unicode编码字符串转中文问题

Qt程序设计之Unicode编码字符串转中文问题,就是要替换掉前面的“\\u”,再将4位16进制数转成QChar类型,问题基本解决。下面就用Qt自带的正则表达式解决,方法如下:

QString Unicode2CN(QString data)
{
    QRegularExpression re("\\\\u([0-9a-fA-F]{4})");
    QRegularExpressionMatchIterator it = re.globalMatch(data);

    while(it.hasNext())
    {
        QRegularExpressionMatch match = it.next();
        data.replace(match.captured(0), QChar(match.captured(1).toUShort(NULL, 16)));
    }

    return data;
}

验证代码

    QString data = "\\u71d5\\u4eac\\u5bd3\\u5ba2";
    qDebug() << Unicode2CN(data); // 输出中文:燕京寓客

Leave a Reply

Your email address will not be published.