gpt4 book ai didi

c++ - 处理 std::wstring 和 std::string 之间的 UTF-8 编码字符串

转载 作者:太空狗 更新时间:2023-10-29 20:30:32 27 4
gpt4 key购买 nike

我正在使用两个库,一个在 std::wstring 中存储 UTF-8 字符串,另一个在 std::string 中存储字符串 (UTF-8)。< br/>我可以用来在两个库之间传递字符串的最佳/有效方法是什么。
我目前在 Windows 上使用 Visual C++ v9 Express,但更喜欢可移植解决方案。

最佳答案

假设您指的是 UTF-16 而不是 std::wstring 的 UTF-8,您将必须将字符串从一个库编码/解码到另一个库。我不确定 STL 是否为此提供了什么,但您可以使用 Windows 自己的 MultiByteToWideChar()WideCharToMultiByte() 函数在 UTF-8 和 UTF 之间进行转换-16 只需几行代码。然后您可以将其包装到您自己的函数中,以便在您发现更便携的东西时替换逻辑,例如:

std::wstring Utf8ToUtf16(const std::string &s)
{
std::wstring ret;
int len = MultiByteToWideChar(CP_UTF8, 0, s.c_str(), s.length(), NULL, 0);
if (len > 0)
{
ret.resize(len);
MultiByteToWideChar(CP_UTF8, 0, s.c_str(), s.length(), const_cast<wchar_t*>(ret.c_str()), len);
}
return ret;
}

std::string Utf16ToUtf8(const std::wstring &s)
{
std::string ret;
int len = WideCharToMultiByte(CP_UTF8, 0, s.c_str(), s.length(), NULL, 0, NULL, NULL);
if (len > 0)
{
ret.resize(len);
WideCharToMultiByte(CP_UTF8, 0, s.c_str(), s.length(), const_cast<char*>(ret.c_str()), len, NULL, NULL);
}
return ret;
}

关于c++ - 处理 std::wstring 和 std::string 之间的 UTF-8 编码字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6864064/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com