恢复运行时unicode字符串

restore runtime unicode strings

本文关键字:字符串 unicode 运行时 恢复      更新时间:2023-10-16

我正在构建一个通过tcp接收编码unicode的运行时字符串的应用程序,一个示例字符串将是"u7cfbu8ecau4e21uff1au6771u5317…"。我有以下内容,但不幸的是,我只能在编译时从中受益,因为:不完整的通用字符名称u,因为它在编译时期望4个十六进制字符。

QString restoreUnicode(QString strText)
   {
      QRegExp rx("\\u([0-9a-z]){4}");
      return strText.replace(rx, QString::fromUtf8("u\1"));
   }

我在运行时寻求解决方案,我可以预见分解这些字符串,并做一些操作,将"u"分隔符后的十六进制转换为基数10,然后将它们传递给QChar的构造函数,但我正在寻找一个更好的方法,如果存在,因为我非常关心这种方法所产生的时间复杂性,我不是专家。

谁有什么解决方案或技巧?

您应该自己解码字符串。只需取Unicode条目(rx.indexIn(strText)),解析它(int result; std::istringstream iss(s); if (!(iss>>std::hex>>result).fail()) ...)并将原始字符串\uXXXX替换为(wchar_t)result

对于关闭和将来遇到此线程的任何人,这是我在优化这些变量的作用域之前的初始解决方案。不是它的粉丝,但它的工作给予不可预测的性质的unicode和/或ascii在我无法控制的流(仅限客户端),而unicode的存在是低的,这是很好的处理它,而不是丑陋的u1234等。

QString restoreUnicode(QString strText)
{
    QRegExp rxUnicode("\\u([0-9a-z]){4}");
    bool bSuccessFlag;
    int iSafetyOffset = 0;
    int iNeedle = strText.indexOf(rxUnicode, iSafetyOffset);
    while (iNeedle != -1)
    {
        QChar cCodePoint(strText.mid(iNeedle + 2, 4).toInt(&bSuccessFlag, 16));
        if ( bSuccessFlag )
            strText = strText.replace(strText.mid(iNeedle, 6), QString(cCodePoint));
        else
            iSafetyOffset = iNeedle + 1; // hop over non code point to avoid lock
        iNeedle = strText.indexOf(rxUnicode, iSafetyOffset);
    }
    return strText;
}
#include <assert.h>
#include <iostream>
#include <string>
#include <sstream>
#include <locale>
#include <codecvt>          // C++11
using namespace std;
int main()
{
    char const  data[]  = "\u7cfb\u8eca\u4e21\uff1a\u6771\u5317";
    istringstream   stream( data );
    wstring     ws;
    int         code;
    char        slashCh, uCh;
    while( stream >> slashCh >> uCh >> hex >> code )
    {
        assert( slashCh == '' && uCh == 'u' );
        ws += wchar_t( code );
    }
    cout << "Unicode code points:" << endl;
    for( auto it = ws.begin();  it != ws.end();  ++it )
    {
        cout << hex << 0 + *it << endl;
    }
    cout << endl;
    // The following is C++11 specific.
    cout << "UTF-8 encoding:" << endl;
    wstring_convert< codecvt_utf8< wchar_t > >  converter;
    string const bytes = converter.to_bytes( ws );
    for( auto it = bytes.begin();  it != bytes.end();  ++it )
    {
        cout << hex << 0 + (unsigned char)*it << ' ';
    }
    cout << endl;
}