使用C++11 Locale轉換文本編碼

C++11標準增加了一些新的類模板用於改進對國際化和本地化的支持。其中,std::wstring_convert、std::codecvt_utf8等類的出現解決了以往C++難以實現在Unicode到UTF-8以及CJK等本地多字節編碼之間轉換文本的問題,現在終於不用再去勞煩第三方庫和MultiByteToWideChar/WideCharToMultiByte等繁瑣的WindowsAPI了。

下面的代碼演示瞭如何利用這些新類,結合原有的codecvt機制,將UTF-8編碼的原始字符串轉換爲Unicode,然後再轉換爲中文GBK編碼。

InBlock.gif#include<tchar.h>
InBlock.gif#include<locale>
InBlock.gif#include<codecvt>
InBlock.gif#include<iostream>
InBlock.gif
InBlock.gifint_tmain(intargc,_TCHAR*argv[])
InBlock.gif{
InBlock.gifstd::stringmystring("\xe4\xb8\xad\xe6\x96\x87");//UTF-8編碼的“中文”字符串
InBlock.gifstd::wstring_convert<std::codecvt_utf8<wchar_t>>cvt_utf8;//UTF-8<->Unicode轉換器
InBlock.gifstd::wstring_convert<std::codecvt<wchar_t,char,std::mbstate_t>>cvt_ansi(newstd::codecvt<wchar_t,char,std::mbstate_t>("CHS"));//GBK<->Unicode轉換器
InBlock.gifstd::wstringws=cvt_utf8.from_bytes(mystring);//UTF-8轉換爲Unicode
InBlock.gifstd::stringmyansistr=cvt_ansi.to_bytes(ws);//Unicode轉換爲GBK
InBlock.gifstd::cout<<myansistr<<std::endl;
InBlock.gifreturn0;
InBlock.gif}

注:以上代碼在VisualStudio2010SP1/2012環境下編譯通過。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章