私は wstring を持っています。それをエスケープされた形式の文字列に変換する最良の方法は何\u043d\u043e\u043c\u0430
ですか?
以下のものは機能しますが、最善ではないようです。
string output;
for (wchar_t chr : wtst) {
char code[7];
sprintf(code,"\\u%0.4X",chr);
output += code;
}
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);
}