这个功能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;
}
这段代码的原理很简单:
测试了用例没有问题。测试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库。