c++ utf8转gbk怎么实现

   2024-10-01 4500
核心提示:在C++中,可以使用Windows API中的MultiByteToWideChar和WideCharToMultiByte函数来实现UTF-8到GBK的转换。这里是一个简单的示例

在C++中,可以使用Windows API中的MultiByteToWideChar和WideCharToMultiByte函数来实现UTF-8到GBK的转换。这里是一个简单的示例代码:

#include <windows.h>#include <iostream>#include <string>std::string utf8_to_gbk(const std::string& utf8_str) {    int len = MultiByteToWideChar(CP_UTF8, 0, utf8_str.c_str(), -1, NULL, 0);    wchar_t* wstr = new wchar_t[len];    MultiByteToWideChar(CP_UTF8, 0, utf8_str.c_str(), -1, wstr, len);    len = WideCharToMultiByte(CP_ACP, 0, wstr, -1, NULL, 0, NULL, NULL);    char* gbk_str = new char[len];    WideCharToMultiByte(CP_ACP, 0, wstr, -1, gbk_str, len, NULL, NULL);    std::string result(gbk_str);    delete[] wstr;    delete[] gbk_str;    return result;}int main() {    std::string utf8_str = u8"你好,世界!";    std::string gbk_str = utf8_to_gbk(utf8_str);    std::cout << "GBK string: " << gbk_str << std::endl;    return 0;}

在这个示例中,utf8_to_gbk函数接受一个UTF-8编码的字符串作为参数,并返回一个GBK编码的字符串。通过调用MultiByteToWideChar和WideCharToMultiByte函数,将UTF-8字符串转换为宽字符编码,然后再转换为GBK编码。

需要注意的是,这里使用了Windows特有的编码方式,所以这段代码只能在Windows平台上正常运行。如果需要在其他平台上进行UTF-8到GBK的转换,可能需要使用不同的方法。

 
举报打赏
 
更多>同类物流大全
推荐图文
推荐物流大全
点击排行

网站首页  |  关于我们  |  联系方式 | 网站留言    |  赣ICP备2021007278号