【问题标题】:Conversion from UTF-8 encoded string to bytes and vice versa in C++在 C++ 中从 UTF-8 编码的字符串转换为字节,反之亦然
【发布时间】:2022-01-22 22:28:12
【问题描述】:

在 C# 中,我们有以下函数将字符串转换为 UTF-8 编码的字节序列,反之亦然:

  1. Encoding.UTF8.GetString(Byte[])
  2. Encoding.UTF8.GetBytes(Char[]) / Encoding.UTF8.GetBytes(String)

我正在尝试在 C++ 中实现相同的功能,如下所示:

std::string GetStringFromBytes(std::vector<uint8_t> bytes){
    std::string str(bytes.begin(), bytes.end());
    return str;
}

std::vector<uint8_t> GetBytesFromString(const std::string& str){
    std::vector<uint8_t> bytes(str.begin(), str.end());
    return bytes;
}

这种方法正确吗?我假设我正在转换的字符串已经是 UTF-8 格式。

【问题讨论】:

  • Is this approach correct? - 你试过并查看结果了吗?
  • “正确”是什么意思?
  • std::string 已经有字节,你不必复制它们,只需使用它们。你几乎没有转换任何东西,你在复制。

标签: c++ utf-8 c++14


【解决方案1】:

C# string 使用 UTF-16,因此需要与 UTF-8 进行字符集转换

C++ std::string 不使用 UTF-16(std::u16string 使用)。所以,如果你有一个 UTF-8 编码的std::string,你已经有了它的原始字节,只需照原样复制它们。您显示的代码正是这样做的,并且适用于 UTF-8 字符串。否则,如果您有/需要以其他字符集编码的std::string,您将需要 charset 转换 到/从 UTF-8。有 3rd 方 Unicode 库可以处理,例如 libiconv、ICU 等。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多