sting转wstring
std::wstring AnsiToUnicode(const std::string& strA)
{
int unicodeLen = ::MultiByteToWideChar(CP_ACP, 0, strA.c_str(), -1, NULL, 0);
if (unicodeLen <= 0)
{
return (L"");
}
wchar_t* pUnicode = new wchar_t[unicodeLen + 1];
memset(pUnicode, 0, (unicodeLen + 1)*sizeof(wchar_t));
::MultiByteToWideChar(CP_ACP, 0, strA.c_str(), -1, (LPWSTR)pUnicode, unicodeLen);
std::wstring rt = pUnicode;
delete[] pUnicode;
pUnicode = NULL;
return rt;
}
wstring转string
std::string UnicodeToAnsi(const std::wstring& strW)
{
int iTextLen = WideCharToMultiByte(CP_ACP, 0, strW.c_str(), -1, NULL, 0, NULL, NULL);
if (iTextLen <= 0)
{
return "";
}
char* pElementText = new char[iTextLen + 1];
memset(pElementText, 0, sizeof(char) * (iTextLen + 1));
::WideCharToMultiByte(CP_ACP, 0, strW.c_str(), -1, pElementText, iTextLen, NULL, NULL);
std::string strText = pElementText;
delete[] pElementText;
pElementText = NULL;
return strText;
}
UTF-8转Unicode
//UTF-8 to Unicode
std::wstring UTF8ToUnicode(const std::string& str)
{
int unicodeLen = ::MultiByteToWideChar(CP_UTF8, 0, str.c_str(), -1, NULL, 0);
if (unicodeLen <= 0)
{
return L"";
}
wchar_t* pUnicode = new wchar_t[unicodeLen + 1];
memset(pUnicode, 0, (unicodeLen + 1)*sizeof(wchar_t));
::MultiByteToWideChar(CP_UTF8, 0, str.c_str(), -1, (LPWSTR)pUnicode, unicodeLen);
std::wstring rt = pUnicode;
delete[] pUnicode;
pUnicode = NULL;
return rt;
}
Unicode转UTF-8
//Unicode to UTF-8
std::string UnicodeToUTF8(const std::wstring& str)
{
int iTextLen = WideCharToMultiByte(CP_UTF8, 0, str.c_str(), -1, NULL, 0, NULL, NULL);
if (iTextLen <= 0)
{
return "";
}
char* pElementText = new char[iTextLen + 1];
memset(pElementText, 0, sizeof(char) * (iTextLen + 1));
::WideCharToMultiByte(CP_UTF8, 0, str.c_str(), -1, pElementText, iTextLen, NULL, NULL);
std::string strText = pElementText;
delete[] pElementText;
pElementText = NULL;
return strText;
}
字符串替换
template<class T>
void _StringReplace(T& strExpr, const T& strsrc, const T& strdst, size_t offset)
{
T::size_type pos = offset;
T::size_type srclen = strsrc.size();
T::size_type dstlen = strdst.size();
while ((pos = strExpr.find(strsrc, pos)) != T::npos)
{
strExpr.replace(pos, srclen, strdst);
pos += dstlen;
}
}
void StringReplace(std::string& strExpr, const std::string& strsrc, const std::string& strdst, size_t offset)
{
_StringReplace(strExpr, strsrc, strdst, offset);
}
void StringReplace(std::wstring& strExpr, const std::wstring& strsrc, const std::wstring& strdst, size_t offset)
{
_StringReplace(strExpr, strsrc, strdst, offset);
}
大小写字符转换
std::wstring& StringToUpper(std::wstring& str)
{
for (auto first = str.begin(); first != str.end(); ++first)
{
*first = toupper(*first);
}
return str;
}
std::wstring& StringToLower(std::wstring& str)
{
for (auto first = str.begin(); first != str.end(); ++first)
{
*first = tolower(*first);
}
return str;
}