假设我有一个 std::string
,但数据是用 UTF-16 编码的。
我如何才能将该数据复制到 std::wstring
中,而根本不修改数据?
此外,我不能只使用 std::wstring
,因为我正在在线检索文本文件并检查 Content-Type
header 字段以确定编码。但是使用 std::string
来接收数据。
最佳答案
std::wstring PackUTF16(const std::string & input)
{
if (input.size() % 2 != 0)
throw std::invalid_argument("input length must be even");
std::wstring result(input.size() / 2, 0);
for (int i = 0; i < result.size(); ++i)
{
result[i] = (input[2*i+1] & 0xff) << 8 | (input[2*i] & 0xff); // for little endian
//result[i] = (input[2*i] & 0xff) << 8 | (input[2*i+1] & 0xff); // for big endian
}
return result;
}
关于C++ 将数据从 std::string 复制到 std::wstring,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10247853/