c++11 function transcoding

Source: Internet
Author: User
Tags locale


#include <string>
#include <codecvt>

Using namespace std;

// utf8 to unicode
Wstring utf8_to_wstring(const string &str)
{
    Wstring_convert<codecvt_utf8<wchar_t>> utf8_cvt;
    Return utf8_cvt.from_bytes(str);
}

// unicode to utf8
String wstring_to_utf8(const wstring &str)
{
    Wstring_convert<codecvt_utf8<wchar_t>> utf8_cvt;
    Return utf8_cvt.to_bytes(str);
}

// gbk to unicode
Wstring gbk_to_wstring(const string &str)
{
    Wstring_convert<codecvt<wchar_t, char, mbstate_t>> gbk_cvt(new codecvt<wchar_t, char, mbstate_t>("chs"));
    Return gbk_cvt.from_bytes(str);
}

// unicode to gbk
String wstring_to_gbk(const wstring &str)
{
    Wstring_convert<codecvt<wchar_t, char, mbstate_t>> gbk_cvt(new codecvt<wchar_t, char, mbstate_t>("chs"));
    Return gbk_cvt.to_bytes(str);
}

// utf8 to gbk
String utf8_to_gbk(const string &str)
{
    Wstring_convert<codecvt_utf8<wchar_t>> utf8_cvt; // utf8-"unicode converter
    Wstring_convert<codecvt<wchar_t, char, mbstate_t>> gbk_cvt(new codecvt<wchar_t, char, mbstate_t>("chs")); // unicode-"gbk converter
    Wstring t = utf8_cvt.from_bytes(str);
    Return gbk_cvt.to_bytes(t);
}

// gbk to utf8
String gbk_to_utf8(const string &str)
{
    Wstring_convert<codecvt_utf8<wchar_t>> utf8_cvt; // utf8-"unicode converter
    Wstring_convert<codecvt<wchar_t, char, mbstate_t>> gbk_cvt(new codecvt<wchar_t, char, mbstate_t>("chs")); // unicode-"gbk converter
    Wstring t = gbk_cvt.from_bytes(str);
    Return utf8_cvt.to_bytes(t);
}




Int main()
{
     Locale::global(locale(""));
     String u8str = u8"I love China i love china";
     String str = "I love China i love china";
     Wstring w1 = gbk_to_wstring(str);
     Str = wstring_to_gbk(w1);
    
     Cout << str << endl;
     Wcout << w1 << endl;

     Return 0;
} 





c++11 function transcoding


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.