0

我有一个 wstring,将它转换为转义形式的字符串的最佳方法是\u043d\u043e\u043c\u0430什么?

下面的一个有效,但似乎不是最好的:

string output; 
for (wchar_t chr : wtst) {
    char code[7];
    sprintf(code,"\\u%0.4X",chr);
    output += code;
}
4

1 回答 1

1

一个不太紧凑但更快的版本,a) 提前分配 b) 避免 printf 每次迭代重新解释格式字符串的成本,c) 避免 printf 的函数调用开销。

std::wstring wstr(L"\x043d\x043e\x043c\x0430");
std::string sstr;
// Reserve memory in 1 hit to avoid lots of copying for long strings.
static size_t const nchars_per_code = 6;
sstr.reserve(wstr.size() * nchars_per_code); 
char code[nchars_per_code];
code[0] = '\\';
code[1] = 'u';
static char const* const hexlut = "0123456789abcdef";
std::wstring::const_iterator i = wstr.begin();
std::wstring::const_iterator e = wstr.end();
for (; i != e; ++i) {
    unsigned wc = *i;
    code[2] = (hexlut[(wc >> 12) & 0xF]);
    code[3] = (hexlut[(wc >> 8) & 0xF]);
    code[4] = (hexlut[(wc >> 4) & 0xF]);
    code[5] = (hexlut[(wc) & 0xF]);
    sstr.append(code, code + nchars_per_code);
}
于 2013-03-21T14:35:09.387 回答