字符串间的转换
CString 转char *
char *p = (LPSTR)(LPCTSTR)cstr;
string 转 CString
CString.format(”%s”, string.c_str());
char 转 CString
CString.format(”%s”, char*);
char 转 string
string s(char *);
string 转 char *
char *p = string.c_str();
CString 转 string
string s(CString.GetBuffer());
CString 转宽字节
用(LPWSTR)强转
_bstr_t 与CString的转换
_bstr_t bstr; CString strSql;
CString -> _bstr_t: bstr = (_bstr_t)strSql;
_bstr_t -> CString: strSql = (LPCSTR)bstr;
_tcstoul()或者_tcstol()
能把字符串转化成任意进制的长整数(如二进制、八进制、十进制或十六进制),不同点在于前者转化后的数据是无符号的(unsigned),而后者相反。
字符串转整形
int my_atoi(const char* p){
assert(p != NULL);
bool neg_flag = false;// 符号标记
int res = 0;// 结果
if(p[0] == '+' || p[0] == '-')
neg_flag = (*p++ != '+');
while(isdigit(*p)) res = res*10 + (*p++ - '0');
return neg_flag ?0 -res : res;
}
char *strrchr(char *str, char c);
查找一个字符c在另一个字符串str中末次出现的位置。
查找字符串s中首次出现字符c的位置。
char *strstr(char *str1, char *str2);
整形跟4字符之间的转换
int a = 2742;
xx[0] = a>>24&0xff;
xx[1] = a>>16&0xff;
xx[2] = a>>8&0xff;
xx[3] = a&0xff;
int f = (xx[0]&0xff)<<24|(xx[1]&0xff)<<16|(xx[2]&0xff)<<8|(xx[3]&0xff);
/*当byte要转化为int的时候,高的24位必然会补1,这样,其二进制补码其实已经不一致了,&0xff可以将高的24位置为0,低8位保持原样。这样做的目的就是为了保证二进制数据的一致性。当然拉,保证了二进制数据性的同时,如果二进制被当作byte和int来解读,其10进制的值必然是不同的,因为符号位位置已经发生了变化。*/
字符串转整形的函数
/*
param:a为字符串
param:n为字符串的前n位
*/
unsigned int chartoint(char a[],int n)
{
if (n>4)
{
return -1;
}
unsigned int num = 0;
for (int i =0;i<n;i++)
{
num<<=8;
num|=a[i];
}
return num;
}
string 转UTF8
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;
}
UTF8转string
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;
}