C++中字串有很多種類,詳情參考C++中的字串型別,本文主要以string型別為例,講一下字串的編碼,選擇string主要是因為:
- byte是字串二進制編碼的最小結構,字串本質上就是一個byte陣列
- C++沒有byte型別,第三方的byte型別通常是char實作的
- char可以直接轉換成string,也就是說byte直接轉string
代碼轉自utf8與std::string字符編碼轉換,其它編碼格式的轉換方法類似(先轉雙位元組Unicode編碼,再通過轉換為其它編碼的多位元組),代碼如下:
std::string UTF8_To_string(const std::string& str)
{
int nwLen = MultiByteToWideChar(CP_UTF8, 0, str.c_str(), -1, NULL, 0);
wchar_t* pwBuf = new wchar_t[nwLen + 1];//加1用于截斷字串
memset(pwBuf, 0, nwLen * 2 + 2);
MultiByteToWideChar(CP_UTF8, 0, str.c_str(), str.length(), pwBuf, nwLen);
int nLen = WideCharToMultiByte(CP_ACP, 0, pwBuf, -1, NULL, NULL, NULL, NULL);
char* pBuf = new char[nLen + 1];
memset(pBuf, 0, nLen + 1);
WideCharToMultiByte(CP_ACP, 0, pwBuf, nwLen, pBuf, nLen, NULL, NULL);
std::string retStr = pBuf;
delete[]pBuf;
delete[]pwBuf;
pBuf = NULL;
pwBuf = NULL;
return retStr;
}
std::string string_To_UTF8(const std::string& str)
{
int nwLen = ::MultiByteToWideChar(CP_ACP, 0, str.c_str(), -1, NULL, 0);
wchar_t* pwBuf = new wchar_t[nwLen + 1];//加1用于截斷字串
ZeroMemory(pwBuf, nwLen * 2 + 2);
::MultiByteToWideChar(CP_ACP, 0, str.c_str(), str.length(), pwBuf, nwLen);
int nLen = ::WideCharToMultiByte(CP_UTF8, 0, pwBuf, -1, NULL, NULL, NULL, NULL);
char* pBuf = new char[nLen + 1];
ZeroMemory(pBuf, nLen + 1);
::WideCharToMultiByte(CP_UTF8, 0, pwBuf, nwLen, pBuf, nLen, NULL, NULL);
std::string retStr(pBuf);
delete[]pwBuf;
delete[]pBuf;
pwBuf = NULL;
pBuf = NULL;
return retStr;
}
注:string使用的ANSI編碼,在簡體中文系統下ANSI編碼代表GB2312編碼,
MultiByteToWideChar和WideCharToMultiByte用法參考MultiByteToWideChar和WideCharToMultiByte用法詳解
,方法的第一個引數是指定指標所指字串記憶體的編碼格式,內容如下:
| Value | Description |
|---|---|
| CP_ACP | ANSI code page |
| CP_MACCP | Not supported |
| CP_OEMCP | OEM code page |
| CP_SYMBOL | Not supported |
| CP_THREAD_ACP | Not supported |
| CP_UTF7 | UTF-7 code page |
| CP_UTF8 | UTF-8 code page |
兩個方法都會呼叫兩次,第一次呼叫最后一個引數(目標字串長度)為0,方法回傳目標字串長度的長度,第二次呼叫時,最后一個引數傳入目標字串長度+1,直接在緩沖區寫入轉換后的字串,
注:在linux下也有類似的兩個函式:mbstowcs()、wcstombs(),使用方法參考https://blog.csdn.net/yiyaaixuexi/article/details/6174971,
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/308147.html
標籤:C++
