zoukankan      html  css  js  c++  java
  • 多字节、Unicode和UTF8字符串的互换

    .

     

    实现过程

    .

     

    #include "stdafx.h"
    #include <windows.h>
    #include <iostream>
    #include <string>
    using namespace std;
    string Unicode2Ascii(wstring wstrsrc);
    wstring Ascii2Unicode(string astrsrc);
    string Unicode2UTF8(wstring wstrsrc);
    wstring UTF82Unicode(string utf8strsrc);
    int main(int argc, char* argv[])
    {
        char szText[] = "这是一个ANSI转化为UTF8的例子!\r\n";
        wstring strUnicode;
        string strAnsistrUTF8;
        strAnsi = szText;
        strUnicode = Ascii2Unicode(strAnsi);
        strUTF8 = Unicode2UTF8(strUnicode);
        cout << strUTF8 << endl;
        
        strUnicode = UTF82Unicode(strUTF8);
        strAnsi = Unicode2Ascii(strUnicode);
        cout << strAnsi << endl;
        return 0;
    }
    string Unicode2Ascii(wstring wstrsrc)
    {
        int nLength = ::WideCharToMultiByte(CP_OEMCP0wstrsrc.c_str(), -1NULL0NULLNULL);
        if(nLength <= 0) return string("");
        char *szbuffer = new char[nLength + 2];
        ::WideCharToMultiByte(CP_OEMCP0wstrsrc.c_str(), -1szbuffernLengthNULLNULL);
        string strnew = szbuffer;
        delete [] szbuffer;
        return strnew;
    }
    wstring Ascii2Unicode(string astrsrc)
    {
        int nLength = ::MultiByteToWideChar(CP_ACP0astrsrc.c_str(), -1NULL0);
        if(nLength <= 0) return wstring(L"");
        wchar_t *szbuffer = new wchar_t[nLength + 2];
        ::MultiByteToWideChar(CP_ACP0astrsrc.c_str(), -1szbuffernLength);
        wstring strnew = szbuffer;
        delete [] szbuffer;
        return strnew;
    }
    string Unicode2UTF8(wstring wstrsrc)
    {
        int nLength = ::WideCharToMultiByte(CP_UTF80wstrsrc.c_str(), -1NULL0NULLNULL);
        if(nLength <= 0) return string("");
        char *szbuffer = new char[nLength + 2];
        ::WideCharToMultiByte(CP_UTF80wstrsrc.c_str(), -1szbuffernLengthNULLNULL);
        string strnew = szbuffer;
        delete [] szbuffer;
        return strnew;
    }
    wstring UTF82Unicode(string utf8strsrc)
    {
        int nLength = ::MultiByteToWideChar(CP_UTF80utf8strsrc.c_str(), -1NULL0);
        if(nLength <= 0) return wstring(L"");
        wchar_t *szbuffer = new wchar_t[nLength + 2];
        ::MultiByteToWideChar(CP_UTF80utf8strsrc.c_str(), -1szbuffernLength);
        wstring strnew = szbuffer;
        delete [] szbuffer;
        return strnew;
    }

    .

    .

    .

    备注

    .

    .关键点

    .

    相关链接

    相关链接    相关链接

    相关链接    相关链接.

    .




  • 相关阅读:
    uva 11294 Wedding
    uvalive 4452 The Ministers’ Major Mess
    uvalive 3211 Now Or Later
    uvalive 3713 Astronauts
    uvalive 4288 Cat Vs. Dog
    uvalive 3276 The Great Wall Game
    uva 1411 Ants
    uva 11383 Golden Tiger Claw
    uva 11419 SAM I AM
    uvalive 3415 Guardian Of Decency
  • 原文地址:https://www.cnblogs.com/xe2011/p/3049003.html
Copyright © 2011-2022 走看看