溫馨提示×

c++ utf8轉(zhuǎn)gbk怎么實(shí)現(xiàn)

c++
小億
144
2024-08-11 13:24:35
欄目: 編程語言

在C++中,可以使用Windows API中的MultiByteToWideChar和WideCharToMultiByte函數(shù)來實(shí)現(xiàn)UTF-8到GBK的轉(zhuǎn)換。這里是一個(gè)簡單的示例代碼:

#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;
}

在這個(gè)示例中,utf8_to_gbk函數(shù)接受一個(gè)UTF-8編碼的字符串作為參數(shù),并返回一個(gè)GBK編碼的字符串。通過調(diào)用MultiByteToWideChar和WideCharToMultiByte函數(shù),將UTF-8字符串轉(zhuǎn)換為寬字符編碼,然后再轉(zhuǎn)換為GBK編碼。

需要注意的是,這里使用了Windows特有的編碼方式,所以這段代碼只能在Windows平臺(tái)上正常運(yùn)行。如果需要在其他平臺(tái)上進(jìn)行UTF-8到GBK的轉(zhuǎn)換,可能需要使用不同的方法。

0