Как указать код utf-8 в литералах QString? - PullRequest
0 голосов
/ 03 апреля 2020
QString s="hello";
s.replace("\0xc2\0xa0"," ");
qDebug()<<s;

В приведенном выше коде я хочу заменить возможные неразрывные пробелы (0xc2a0) на "&nbsp;", но на выходе получится

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

, почему? Было бы лучше не использовать другую функцию для преобразования литерала в UFT-8.

1 Ответ

1 голос
/ 03 апреля 2020
#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();
}
...