我目前正在使用Windows API 的方法MultiByteToWideChar和在和之间进行转换。WideCharToMultiBytestd::stringstd::wstring
我正在“多平台”我的代码,删除 Windows 依赖项,所以我想知道上述方法的替代方法。具体来说,使用boost会很棒。我可以使用哪些方法?这是我当前使用的代码:
const std::wstring Use::stow(const std::string& str)
{
if (str.empty()) return L"";
int size_needed = MultiByteToWideChar(CP_UTF8, 0, &str[0], (int)str.size(), NULL, 0);
std::wstring wstrTo( size_needed, 0 );
MultiByteToWideChar(CP_UTF8, 0, &str[0], (int)str.size(), &wstrTo[0], size_needed);
return wstrTo;
}
const std::string Use::wtos(const std::wstring& wstr)
{
if (wstr.empty()) return "";
int size_needed = WideCharToMultiByte(CP_UTF8, 0, &wstr[0], (int)wstr.size(), NULL, 0, NULL, NULL);
std::string strTo( size_needed, 0 );
WideCharToMultiByte (CP_UTF8, 0, &wstr[0], (int)wstr.size(), &strTo[0], size_needed, NULL, NULL);
return strTo;
}
Run Code Online (Sandbox Code Playgroud)
基本上,<cstdlib>您可以使用与已有的类似的实现,如 Joachim Pileborg 所提到的。只要您将区域设置设置为您想要的任何位置(例如:setlocale( LC_ALL, "en_US.utf8" );
MultiByteToWideChar(CP_UTF8, 0, &str[0], (int)str.size(), NULL, 0)=>mbstowcs(nullptr, data(str), size(str))
MultiByteToWideChar(CP_UTF8, 0, &str[0], (int)str.size(), &wstrTo[0], size_needed)=>mbstowcs(data(wstrTo), data(str), size(str))
WideCharToMultiByte(CP_UTF8, 0, &wstr[0], (int)wstr.size(), NULL, 0, NULL, NULL)=>wcstombs(nullptr, data(wstr), size(wstr))
WideCharToMultiByte(CP_UTF8, 0, &wstr[0], (int)wstr.size(), &strTo[0], size_needed, NULL, NULL)=>wcstombs(data(strTo), data(wstr), size(wstr))
编辑:
c++11 要求字符串连续分配,如果您要跨平台编译,这可能很重要,因为以前的标准不需要连续分配string。以前调用&str[0]、&strTo[0]、&wstr[0]或&wstrTo[0]可能会导致问题。
由于c++17现在已成为公认的标准,因此我改进了建议的替换,data而不是取消引用字符串的前面。
| 归档时间: |
|
| 查看次数: |
2644 次 |
| 最近记录: |