我正在使用两个库,一个将UTF-8字符串存储在std::wstring
中,另一个将字符串(UTF-8)存储在std::string
中。
我可以使用什么最好 / 最有效的方法在这两个库之间传递字符串。
我目前正在使用Windows操作系统,使用Visual C++ v9 Express,但希望找到一个可移植的解决方案。
std::wstring
使用的是 UTF-16 而不是 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_str
返回一个const C字符串。但是因为走在正确的道路上而加1分。 - dalleconst_cast
强制转换。 - Remy Lebeauwchar_t
是 UTF-16 则是特定于 Windows 的。 - dan04iconv
。这甚至符合 POSIX 标准。 - Kerrek SB
std::wstring
,那么它很可能使用/期望UTF-16。这是有道理的,因为UTF-8和UTF-16只是相同Unicode字符集的不同编码。数据库可以使用除UTF-8之外的任何字符集,并且ODBC可能会在内部处理它并仍然使用UTF-16来传递数据以保持一致性。 - Remy Lebeauà
,那么wstring[0]的十进制或十六进制值是多少? - Mark Ransom