c++常用字节字符串转换方法
1.string转LPCWSTR
百度的都是这个方法有问题,会导致闪退
LPCWSTR stringToLPCWSTR(string orig)
{
size_t origsize = orig.length() + 1;
const size_t newsize = 100;
size_t convertedChars = 0;
wchar_t *wcstring = (wchar_t *)malloc(sizeof(wchar_t)*(orig.length()-1));
mbstowcs_s(&convertedChars, wcstring, origsize, orig.c_str(), _TRUNCATE);
std::wstring wstrResult(wcstring);
free(wcstring);
return wstrResult.c_str();
}
所以用了这个
//CString
LPCWSTR stringToLPCWSTR(std::string orig)
{
CString result(orig.c_str());
return result;
}
2.LPCWSTR转string
string LPCWSTRTostring(LPCWSTR lpcwszStr)
{
string str;
DWORD dwMinSize = 0;
LPSTR lpszStr = NULL;
dwMinSize = WideCharToMultiByte(CP_OEMCP, NULL, lpcwszStr, -1, NULL, 0, NULL, FALSE);
if (0 == dwMinSize)
{
return FALSE;
}
lpszStr = new char[dwMinSize];
WideCharToMultiByte(CP_OEMCP, NULL, lpcwszStr, -1, lpszStr, dwMinSize, NULL, FALSE);
str = lpszStr;
delete[] lpszStr;
return str;
}
3.utf8中文转Unicode
std::wstring utf8string2wstring(const std::string& str)
{
static std::wstring_convert< std::codecvt_utf8<wchar_t> > strCnv;
return strCnv.from_bytes(str);
}
// string的编码方式为除utf8外的其它编码方式,可采用:
std::string wstring2string(const std::wstring& str, const std::string& locale)
{
typedef std::codecvt_byname<wchar_t, char, std::mbstate_t> F;
static std::wstring_convert<F> strCnv(new F(locale));
return strCnv.to_bytes(str);
}
使用方法
std::string result= wstring2string(utf8string2wstring(ori), “Chinese”);
4.替换字符串中所有指定字符
//下面是一个检查一个字符串中是否有'.'的函数,该函数将找到的'.'转化为'_'。
void checkName(string& name, char* findStr, char* changeStr)
{
std::string::size_type startpos = 0;
while (startpos != std::string::npos)
{
startpos = name.find(findStr); //找到'.'的位置
char* ch = changeStr;
if (startpos != std::string::npos) //std::string::npos表示没有找到该字符
{
name.replace(startpos, 1, ch); //实施替换,注意后面一定要用""引起来,表示字符串
}
}
}
5.string转wchar_t *
wchar_t *multiByteToWideChar(string& pKey)
{
char* pCStrKey = (char*)pKey.c_str();
//第一次调用返回转换后的字符串长度,用于确认为wchar_t*开辟多大的内存空间
int pSize = MultiByteToWideChar(CP_OEMCP, 0, pCStrKey, strlen(pCStrKey) + 1, NULL, 0);
wchar_t *pWCStrKey = new wchar_t[pSize];
//第二次调用将单字节字符串转换成双字节字符串
MultiByteToWideChar(CP_OEMCP, 0, pCStrKey, strlen(pCStrKey) + 1, pWCStrKey, pSize);
return pWCStrKey;
}