字符的 UTF-8 转换

UTF-8 conversion for characters

本文关键字:转换 UTF-8 字符      更新时间:2023-10-16

我目前有一个std::string,它包含这个

"xa9 2006 FooWorld"

基本上它包含符号 © .此字符串将传递给采用 UTF-8 的外部 API 的方法。如何使此字符串 UTF-8 兼容?任何建议。我在这里读到我可以使用std::wstring_convert但我不确定如何在我的情况下应用它。任何建议将不胜感激。

这很简单:使用 UTF-8 字符串文字:

u8"u00A9 2006 FooWorld"

这将导致const char[]是正确编码的 UTF-8 字符串。

在 C++11 及更高版本中,获取 UTF-8 编码字符串文本的最佳方法是使用u8前缀:

std:string str = u8"u00A9 2006 FooWorld";

或:

std:string str = u8"© 2006 FooWorld";

但是,您也可以使用std::wstring_convert,(特别是如果您的输入数据不是字符串文字):

#include <codecvt>
#include <locale>
#include <string>
std::wstring wstr = L"© 2006 FooWorld"; // or whatever...
std::wstring_convert<std::codecvt_utf8<wchar_t>, wchar_t> convert;
std::string str = convert.to_bytes(wstr);