多字節字符串與寬字符串的轉換

多字節字符串與寬字符串的轉換可使用C API者Win32 API.
C API: mbstowcs,wcstombs
Win32 API: MultiByteToWideChar, WideCharToMultiByte

下面着重介紹Win32 API的用法,C API的用法較爲簡單可參照Win32 API。

首先是WideCharToMultiByte

通常你需要配置4個參數(其他參數如是使用即可),紅色標記的部分。
依次是源寬字符串,需要轉換的長度(-1,則爲轉換整個字符串),目標多字節字符串,目標緩衝區長度。
返回值表示轉換爲目標多字節字符串實際需要的長度(包括結束符)。
所以通常需要調用WideCharToMultiByte兩次:第一次產生目標緩衝區長度,第二次產生目標字符串,像下面這樣
wchar_t* wcs = L"中國,你好!I Love You!";
int lengthOfMbs = WideCharToMultiByte( CP_ACP, 0, wcs, -1, NULL, 0, NULL, NULL);
char* mbs = new char[ lengthOfMbs ];
WideCharToMultiByte( CP_ACP, 0, wcs, -1, mbs, lengthOfMbs, NULL, NULL);  
delete mbs;
mbs = NULL;
MultiByteToWideChar的用法類似
char* mbs = "中國,你好!I Love You!";
int lengthOfWcs = MultiByteToWideChar( CP_ACP, 0, mbs, -1, NULL, 0 );
wchar_t* wcs = new wchar_t[ lengthOfWcs ];
MultiByteToWideChar( CP_ACP, 0, mbs, -1, wcs, lengthOfWcs );
delete wcs;
wcs = NULL;

下面兩個函數封裝了轉換過程
#include
#include

std::string WcsToMbs( const std::wstring& wcs ) {  
    int lengthOfMbs = WideCharToMultiByte( CP_ACP, 0, wcs.c_str(), -1, NULL, 0, NULL, NULL);
    char* mbs = new char[ lengthOfMbs ];
    WideCharToMultiByte( CP_ACP, 0, wcs.c_str(), -1, mbs, lengthOfMbs, NULL, NULL);
    std::string result = mbs;
    delete mbs;
    mbs = NULL;
    return result;
}

std::wstring MbsToWcs( const std::string& mbs ) {  
    int lengthOfWcs = MultiByteToWideChar( CP_ACP, 0, mbs.c_str(), -1, NULL, 0 );
    wchar_t* wcs = new wchar_t[ lengthOfWcs ];
    MultiByteToWideChar( CP_ACP, 0, mbs.c_str(), -1, wcs, lengthOfWcs );
    std::wstring result = wcs;
    delete wcs;
    wcs = NULL;
    return result;
}

發佈了139 篇原創文章 · 獲贊 3 · 訪問量 31萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章