写这篇博文的初衷就是让大家更好用类型转换。不然每次都找很麻烦,希望大家可以在下面添加,不断累积。

期间引用了多名博主,整合一波

1.const char * 转 wchar_t*类型:

//const char*转wchar_t*
wchar_t* charToWChart(const char *str)
{
int length = strlen(str)+1;
wchar_t *t = (wchar_t*)malloc(sizeof(wchar_t)*length);
memset(t,0,length*sizeof(wchar_t));
MultiByteToWideChar(CP_ACP,0,str,strlen(str),t,length);
return t;
}

2.std::string字符串替换

//替换字符串
//@param: pszSrc:原先字符串
//@param: pszOld:需要替换的字符串
//@param: pszNew:替换的新字符串
//@return:替换完成的字符串
static std::string replace_str(const char *pszSrc, const char *pszOld, const char *pszNew)
{
std::string strContent, strTemp;
strContent.assign( pszSrc );
std::string::size_type nPos = 0;
while( true )
{
nPos = strContent.find(pszOld, nPos);
strTemp = strContent.substr(nPos+strlen(pszOld), strContent.length());
if ( nPos == std::string::npos )
{
break;
}
strContent.replace(nPos,strContent.length(), pszNew );
strContent.append(strTemp);
nPos +=strlen(pszNew) - strlen(pszOld)+1; //防止重复替换 避免死循环
}
return strContent;
}

3.char*转std::wstring

std::wstring charToWstring(char* szIn)
{
int length = MultiByteToWideChar(CP_ACP, 0, szIn, -1, NULL, 0);
WCHAR* buf = new WCHAR[length+1];
ZeroMemory(buf, (length + 1) * sizeof(WCHAR));
MultiByteToWideChar(CP_ACP, 0, szIn, -1, buf, length);
std::wstring strRet(buf);
delete[] buf;
return strRet;
}

4.wchar_t*转std::string

std::string w2a(wchar_t* szIn)
{
int nSize = WideCharToMultiByte(CP_ACP, 0, szIn, -1, NULL, NULL, NULL, NULL);
char* buffer = new char[nSize+1];
ZeroMemory(buffer,nSize+1);
WideCharToMultiByte(CP_ACP, 0, szIn, -1, buffer, nSize, NULL, NULL);
std::string strRet(buffer);
delete[] buffer;
return strRet;
}

5.std::string判断结尾是否包含某字符:

//判断字符串结尾是否包含某字符;
//[in]s:字符串,[in]sub:包含字符
//return:1:包含 0:包含
bool endsWith(std::string s, std::string sub) {
return s.rfind(sub) == (s.length() - sub.length()) ? true : false;
}

6.分割字符串

//分割字符串
std::vector<std::string> split_str(std::string str, std::string pat)
{
std::vector<std::string> bufStr;
while (true)
{
int index = str.find(pat);
std::string subStr = str.substr(0, index);
if (!subStr.empty())
bufStr.push_back(subStr);

str.erase(0, index + pat.size());

if (index == -1)
break;
}
return bufStr;
}