如何将wstring转换为字符串作为转义

时间:2013-03-21 14:21:12

标签: c++ boost wstring

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

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

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

1 个答案:

答案 0 :(得分: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);
}