L o a d i n g . . .
主打一个C++
文章详情

C++文本转换(utf8与ansi编码互转)

Posted on 2019-11-06 20:03:10 by 主打一个C++

//Utf8转Ansi编码

std::string Utf8ToAnsi(const std::string& utf8Str) {
    // 计算需要的缓冲区大小
    int size = MultiByteToWideChar(CP_UTF8, 0, utf8Str.c_str(), -1, NULL, 0);

    // 创建一个宽字符缓冲区
    std::wstring wideStr(size, L'\0');

    // 将 UTF-8 转换为宽字符
    MultiByteToWideChar(CP_UTF8, 0, utf8Str.c_str(), -1, &wideStr[0], size);

    // 计算新的 ANSI 字符串大小
    size = WideCharToMultiByte(GetACP(), 0, wideStr.c_str(), -1, NULL, 0, NULL, NULL);

    // 创建 ANSI 字符串缓冲区
    std::string ansiStr(size, '\0');

    // 将宽字符转换为 ANSI
    WideCharToMultiByte(GetACP(), 0, wideStr.c_str(), -1, &ansiStr[0], size, NULL, NULL);

    return ansiStr;
}

//Ansi编码转Utf8


std::string AnsiToUtf8(const std::string& ansiStr) {
    // 计算需要的缓冲区大小
    int size = MultiByteToWideChar(GetACP(), 0, ansiStr.c_str(), -1, NULL, 0);

    // 创建一个宽字符缓冲区
    std::wstring wideStr(size, L'\0');

    // 将 ANSI 转换为宽字符
    MultiByteToWideChar(GetACP(), 0, ansiStr.c_str(), -1, &wideStr[0], size);

    // 计算新的 UTF-8 字符串大小
    size = WideCharToMultiByte(CP_UTF8, 0, wideStr.c_str(), -1, NULL, 0, NULL, NULL);

    // 创建 UTF-8 字符串缓冲区
    std::string utf8Str(size, '\0');

    // 将宽字符转换为 UTF-8
    WideCharToMultiByte(CP_UTF8, 0, wideStr.c_str(), -1, &utf8Str[0], size, NULL, NULL);

    return utf8Str;
}


*转载请注明出处:原文链接:https://cpp.vin/page/103.html

作者近期文章
  • 随手笔记
  • 主打一个C++   2025-01-11 20:02:01
  • 都2000000025年了。还有不能随意访问guthub的,仔细看。在国内其实是可以正常访问的,gfw并没屏蔽。这里给出其中一个简单直接的方法稳定访问。1. 随便百度一个”dn
提示
×
确定
数据库执行: 8次 总耗时: 0.01s
页面加载耗时: 



wechat +447752296473
wechat cpp-blog