C++實現(xiàn)String與UF8互轉(zhuǎn)
更新時間:2022年05月04日 17:08:54 作者:農(nóng)碼一生
這篇文章介紹了C++實現(xiàn)String與UF8互轉(zhuǎn)的方法,文中通過示例代碼介紹的非常詳細。對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
UTF8_To_String
#include<Stringapiset.h>
#include <iostream>
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,不然會出現(xiàn)尾巴
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;
}String_To_UTF8
#include<Stringapiset.h>
#include <iostream>
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,不然會出現(xiàn)尾巴
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;
}到此這篇關(guān)于C++實現(xiàn)String與UF8互轉(zhuǎn)的文章就介紹到這了。希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
您可能感興趣的文章:
- C++ string與int的相互轉(zhuǎn)換(使用C++11)
- C++ 字符串string和整數(shù)int的互相轉(zhuǎn)化操作
- C++中string轉(zhuǎn)換為char*類型返回后亂碼問題解決
- C++編程之CString、string與、char數(shù)組的轉(zhuǎn)換
- C++中CString string char* char 之間的字符轉(zhuǎn)換(多種方法)
- 詳解NSString 與C++ string字符串的互轉(zhuǎn)
- C++中string與int的相互轉(zhuǎn)換實現(xiàn)代碼
- C++中將string類型轉(zhuǎn)化為int類型
- 深入理解c++中char*與wchar_t*與string以及wstring之間的相互轉(zhuǎn)換
相關(guān)文章
一篇文章教你用C語言模擬實現(xiàn)字符串函數(shù)
這篇文章主要介紹了C語言模擬實現(xiàn)字符串函數(shù),開發(fā)程序的時候經(jīng)常使用到一些字符串函數(shù),例如求字符串長度,拷貝字符串……,需要的朋友可以參考下2021-09-09

