【问题标题】:Un-escape unicode strings, can't replace '%' with '\u'取消转义 unicode 字符串,不能用 '\u' 替换 '%'
【发布时间】:2012-10-12 05:31:58
【问题描述】:

我想取消转义像 %uXXXX%uYYYY 这样的 unicode 字符串,所以我尝试了:

QString unescapeUnicode (const QString & src)
{
    return QString::fromUtf8 ( src.replace ("%", "\u").toAscii() );
}

由于\u 不是标准转义序列,它不会编译,

但是QString::fromUtf8 ("\uXXXX\uYYYY") 的输出效果很好,这里可能有什么问题?

【问题讨论】:

    标签: qt4


    【解决方案1】:

    适用于文字字符串的转义不适用于字符串。您需要解析每个字符的 unicode 值并逐个字符地构建字符串。比如这样:

    QString unescapeUnicode(const QString& src)
    {
        QStringList chars = src.split("%u", QString::SkipEmptyParts);
        QChar* qchars = new QChar[chars.size()];
    
        bool ok;
        for (int i = 0; i < chars.size(); ++i)
        {
            qchars[i] = QChar(chars[i].toInt(&ok, 16));
            if (!ok)
                return "ERROR";
        }
    
        QString result(qchars, chars.size());
        delete[] qchars;
        return result;
    }
    

    及用法:

    QString txt = unescapeUnicode("%u00a2%u20ac%u3b2");
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-07-19
      • 2012-03-03
      • 2021-03-28
      • 2016-11-04
      • 2014-09-17
      • 1970-01-01
      • 2017-02-28
      相关资源
      最近更新 更多