Qt翻译转义序列

时间:2016-09-05 10:26:18

标签: c++ qt escaping

我有:

    ºC

我想将其翻译成ºC

我正在使用Qt 5.6,是否有内置函数我可以调用来翻译这个序列?

Qt具有将符号转换为转义序列的功能:

    QString QString::toHtmlEscaped()

但我需要的是相应的功能,以翻译回原文。

3 个答案:

答案 0 :(得分:2)

您可以使用QTextDocumentQTextDocumentFragment解码html实体:

QString html_string = "ºC";
QString plain_string = QTextDocumentFragment::fromHtml(b).toPlainText();

答案 1 :(得分:1)

对于我的项目,为了显示我所做的温度:

    QChar degreesSymbol(0260);
    QString stringToShow = "Your number " + degreesSymbol + "C";

答案 2 :(得分:1)

您可以使用C ++ regexp-s,下面是示例代码。

作为旁注:您可以在此处阅读:https://en.wikipedia.org/wiki/Degree_symbol该学位符号是

U+00B0 ° DEGREE SIGN (HTML ° · °).

&#186适用于:

U+00BA º MASCULINE ORDINAL INDICATOR (HTML º · º) (superscript letter used in abbreviating words; varies with the font and sometimes underlined)

[live]

#include <iostream>
#include <string>
#include <sstream>
#include <regex>

std::string html_unescape_char(int html_escape_code) {
    switch (html_escape_code) {
        case 176:
        return "\u00B0"; // °       
        case 186:
        return "\u00BA"; // º        
        // todo: use std::mbtowc or add other entities (ie. from http://www.freeformatter.com/html-entities.html)

    }
    return "?";
}

std::string html_unescape_string(std::string s) {
    std::regex r(R"((.*?)&#(\d+);)");
    std::ostringstream res;        
    for(std::sregex_iterator it(s.begin(), s.end(), r), end_it; it != end_it; ++it) {        
        res << it->format("$1");
        int html_escape_code = std::stoi((*it)[2]); // !! stoi might throw
        res << html_unescape_char(html_escape_code);
    }
    return res.str();
}

void test(std::string s) {
    std::cout << " in:" << s << "\n" << "out:" << html_unescape_string(s) << "\n\n";
}

int main()
{
    test("&#186;C");
    test("123&#186;C not the same as 123&#176;C");
    test("&#186;C  123&#186;C    1&#186;C");
}