c++中utf8字符串和gbk字符串的转换

这个功能C++语言本身似乎没有标准实现,需要借助于第三方库或者操作系统API。不得不吐槽一下这么重要的功能居然还没有办法依赖C++语言本身来实现,C++标准委员会真是不干人事啊。那就不废话了,直接给出windows下的实现。

std::string Utf8ToGbk(const std::string& utf8Str) {
  // Step 1: Convert UTF-8 to Wide Char (UTF-16)
  int wideCharLen =
      MultiByteToWideChar(CP_UTF8, 0, utf8Str.c_str(), -1, nullptr, 0);
  if (wideCharLen == 0) {
    throw std::runtime_error("Failed to convert from UTF-8 to wide char.");
  }

  std::wstring wideStr(wideCharLen, 0);
  MultiByteToWideChar(CP_UTF8, 0, utf8Str.c_str(), -1, &wideStr[0],
                      wideCharLen);

  // Step 2: Convert Wide Char (UTF-16) to GBK
  int gbkLen = WideCharToMultiByte(CP_ACP, 0, wideStr.c_str(), -1, nullptr, 0,
                                   nullptr, nullptr);
  if (gbkLen == 0) {
    throw std::runtime_error("Failed to convert from wide char to GBK.");
  }

  std::string gbkStr(gbkLen, 0);
  WideCharToMultiByte(CP_ACP, 0, wideStr.c_str(), -1, &gbkStr[0], gbkLen,
                      nullptr, nullptr);

  // Remove the null terminator added by the conversion functions
  gbkStr.pop_back();

  return gbkStr;
}

std::string GbkToUtf8(const std::string& gbkStr) {
  // Step 1: Convert GBK to Wide Char (UTF-16)
  int wideCharLen =
      MultiByteToWideChar(CP_ACP, 0, gbkStr.c_str(), -1, nullptr, 0);
  if (wideCharLen == 0) {
    throw std::runtime_error("Failed to convert from GBK to wide char.");
  }

  std::wstring wideStr(wideCharLen, 0);
  MultiByteToWideChar(CP_ACP, 0, gbkStr.c_str(), -1, &wideStr[0], wideCharLen);

  // Step 2: Convert Wide Char (UTF-16) to UTF-8
  int utf8Len = WideCharToMultiByte(CP_UTF8, 0, wideStr.c_str(), -1, nullptr, 0,
                                    nullptr, nullptr);
  if (utf8Len == 0) {
    throw std::runtime_error("Failed to convert from wide char to UTF-8.");
  }

  std::string utf8Str(utf8Len, 0);
  WideCharToMultiByte(CP_UTF8, 0, wideStr.c_str(), -1, &utf8Str[0], utf8Len,
                      nullptr, nullptr);

  // Remove the null terminator added by the conversion functions
  utf8Str.pop_back();

  return utf8Str;
}

这段代码的原理很简单:

  1. CP_ACP的意思就是本地编码,就是操作系统系统定义的默认编码,依赖于当前操作系统的语言和地区设置。在中文环境下就是GBk系列的中文编码,例如GB2312、GBK或GB18030。
  2. 需要使用宽字节字符串来进行中转,在Windows下,std::wstring是16字节字符串,使用UTF-16编码。这一点有点类似于C#的string和Java的string,都是UTF-16编码。
  3. MultiByteToWideChar和WideCharToMultiByte都是操作系统的C接口,输入和返回的字符串都带'\0',因此转到c++的string需要去掉最后的'\0'字符。这一点需要注意。

测试了用例没有问题。测试Utf8ToGbk:

  // string utfStr = u8"这是一个测试的中文字符串,检查一下";
  // string utfStr = u8"测试";
  string utfStr = u8"abcdefg";

  string gbkStr = Utf8ToGbk(utfStr);

  // cout << gbkStr << "-------" << endl;
  // cout << gbkStr.length() << endl;
  // cout << gbkStr.c_str() << endl;
  // cout << strlen(gbkStr.c_str()) << endl;

测试GbkToUtf8:

#ifdef _WIN32
  SetConsoleOutputCP(65001);
#endif

  // string gbkStr = "测试";
  string gbkStr = "这是一个测试的中文字符串,检查一下";
  // string gbkStr = "abcdefg";
  cout << gbkStr.length() << endl;

  string utfStr = GbkToUtf8(gbkStr);

  cout << utfStr << endl;
  cout << utfStr.length() << endl;

以上是Windows的实现,Linux环境要使用别的办法,例如使用iconv库。

posted @ 2024-09-16 22:23  charlee44  阅读(0)  评论(0编辑  收藏  举报