【问题标题】:How to specify utf-8 code in QString literals?如何在 QString 文字中指定 utf-8 代码?
【发布时间】:2020-07-15 08:42:10
【问题描述】:
QString s="hello";
s.replace("\0xc2\0xa0"," ");
qDebug()<<s;

在上面的代码中,我想将可能的不间断空格(0xc2a0)替换为"&amp;nbsp;",但是输出是

"&nbsp;h&nbsp;e&nbsp;l&nbsp;l&nbsp;o&nbsp;"

,为什么?最好不要使用其他函数将文字转换为 UFT-8。

【问题讨论】:

    标签: qt unicode utf-8 qt5 qstring


    【解决方案1】:
    #include "MainWin.h"
    #include <QtWidgets/QApplication>
    #include <QPlainTextEdit>
    #include <QDebug>
    
    int main(int argc, char *argv[])
    {
        QApplication a(argc, argv);
    
        QPlainTextEdit edit;
    
        // "hello world" string from UTF-8 hexadecimal representation
    
        // UTF-8, normal space (0x20)
        QString hello_world_normal("\x68\x65\x6c\x6c\x6f\x20\x77\x6f\x72\x6c\x64");
    
        qDebug() << hello_world_normal;
        edit.appendPlainText(hello_world_normal);
    
        // UTF-8, non-breaking space (0xC2 0xA0)
        QString hello_world_non_breaking("\x68\x65\x6c\x6c\x6f\xc2\xa0\x77\x6f\x72\x6c\x64");
    
        qDebug() << hello_world_non_breaking;
        edit.appendPlainText(hello_world_non_breaking);
    
        hello_world_non_breaking.replace(QString("\xc2\xa0"), "&nbsp;");
    
        qDebug() << hello_world_non_breaking;
        edit.appendPlainText(hello_world_non_breaking);
    
        edit.show();
    
        return a.exec();
    }
    

    【讨论】:

    • 有效!我不知道为什么我在 x 前加了 0,一定是和别的东西混淆了。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-15
    • 1970-01-01
    • 1970-01-01
    • 2015-08-03
    • 1970-01-01
    相关资源
    最近更新 更多