恢复运行时unicode字符串
restore runtime unicode strings
我正在构建一个通过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;
}
相关文章:
- 如何将unicode字符串从C++传递到delphi
- 将ANSI C字符串转换为UNICODE
- 将 unicode 字符串与 c ++ 符号进行比较?
- 如何在 c++ 中读取用 utf-8 编码的 java unicode 字节字符串
- C++:Unicode 字符串文字的可移植性
- 如何使用 CTypes 将 wchar_t** - 以空结尾的 UNICODE 字符串数组 - 返回到 Python 脚
- 在将 unicode 替换为C++字符串中的空格时出现分段错误
- C++ 原始字符串 Unicode 文字
- Xamarin Android:在 C++ 中将字符串从 C# 封送到 Unicode 字符串的正确方法是什么?
- 如何在 python 包装中使用 unicode 字符串用于带有 cython 的 c++ 类?
- 六角字符串到UTF-8(UNICODE)字符串
- 如何使用poco :: logger记录Unicode字符串
- 将 Unicode 字符/字符串写入文件
- 如何将 Unicode 字符串连接成字符串以传递到 mysql 调用中
- 从终端 C++ 中的字符串中打印出 unicode 字符
- Unicode字符串Visual C 构造函数
- 字符串到 Unicode,Unicode 到十进制码位 (C++)
- 如何让 SWIG 返回 Python 2 中字符串的 unicode 对象
- 如何将 (ICU4C) Unicode 字符串逐个字符复制到另一个 Unicode 字符串
- 如何从Windows中的进程中读取Unicode字符串