zoukankan      html  css  js  c++  java
  • C++ 字符串UTF8与GBK转化

           第一次写博客,有时候在工作中遇到解析XML文件,节点属性值为中文的情况,需要转换编码,VC默认是的是GB2312,遇到中文就出现乱码,下面是UTF-8和GBK2312的互相转换,有画蛇添足的地方,希望各位大神指出:

    #include "windows.h"

    // UTF-8转为GBK2312 [1/18/2017/shike]
     std::string UtfToGbk(const char* utf8)
     {
       int len = MultiByteToWideChar(CP_UTF8, 0, utf8, -1, NULL, 0);
       wchar_t* wstr = new wchar_t[len+1];
       memset(wstr, 0, len+1);
       MultiByteToWideChar(CP_UTF8, 0, utf8, -1, wstr, len);
       len = WideCharToMultiByte(CP_ACP, 0, wstr, -1, NULL, 0, NULL, NULL);
       char* str = new char[len+1];
       memset(str, 0, len+1);
       WideCharToMultiByte(CP_ACP, 0, wstr, -1, str, len, NULL, NULL);
       if(wstr) delete[] wstr;
       return str;
     }

    //GBK转化为UTF8格式
     void ConvertGBKToUtf8(CString &strGBK)
     {
      int len=MultiByteToWideChar(CP_ACP, 0, (LPCTSTR)strGBK, -1, NULL,0);
      wchar_t * wszUtf8 = new wchar_t [len];
      memset(wszUtf8, 0, len);
      MultiByteToWideChar(CP_ACP, 0, (LPCTSTR)strGBK, -1, wszUtf8, len);
      len = WideCharToMultiByte(CP_UTF8, 0, wszUtf8, -1, NULL, 0, NULL, NULL);
      char *szUtf8=new char[len + 1];
      memset(szUtf8, 0, len + 1);
      WideCharToMultiByte (CP_UTF8, 0, wszUtf8, -1, szUtf8, len, NULL,NULL);
      strGBK = szUtf8;
      delete[] szUtf8;
      delete[] wszUtf8;
     }

    爬坑的路上要越怕越勇.....
  • 相关阅读:
    好理解的堆排序
    SpringCloud 整合 Python 服务
    SpringCloud入门总结
    Spring异常集中处理和日志集中打印
    Java枚举类型的理解及在后台响应中的使用
    Elasticsearch合并高亮字段
    Elasticsearch分析器结构组成
    Elasticsearch实现英文区分大小写搜索
    Nginx三大功能
    Elasticsearch Java Client 版本区别及起步(5.X 和6.X)
  • 原文地址:https://www.cnblogs.com/shike8080/p/6297210.html
Copyright © 2011-2022 走看看