Cstring,char*,string 转换

第一部分为ASCII码环境下(VC 6.0)下Cstring

 

Cstring to const char *
 1> 传给未分配内存的const char* (LPCTSTR)指针.
   CString cstr(asdd);
   const char* ch = (LPCTSTR)cstr;
   ch指向的地址和cstr相同。但由于使用const保证ch不会修改,所以安全

2>传给未分配内存的指针.
    CString cstr = "ASDDSD";
    char *ch = cstr.GetBuffer(cstr1.GetLength() + 1);
    cstr.ReleaseBuffer();
    //修改ch指向的值等于修改cstr里面的值.
    //PS:用完ch后,不用delete ch,因为这样会破坏cstr内部空间,容易造成程序崩溃.
  3>第二种用法。把CString 值赋给已分配内存的char *。
    CString cstr1 = "ASDDSD";
    int strLength = cstr1.GetLength() + 1;
    char *pValue = new char[strLength];
    strncpy(pValue, cstr1, strLength);
4>第三种用法.把CString 值赋给已分配内存char[]数组.
    CString cstr1 = "ASDDSD";
    int strLength1 = cstr1.GetLength() + 1;
    char chArray[100];
    memset(chArray,0, sizeof(bool) * 100); //将数组的垃圾内容清空
   strncpy(chArray, cstr1, strLength1);

char * 转 Cstring
  1>直接赋值
  2>Csrting.Format();
int  转 Cstring
 Cstring.Format()
Cstring 转 int
  atoi()


        
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());
  
  1,string -> CString
  CString.format("%s", string.c_str());
  用c_str()确实比data()要好.
  2,char -> string
  string s(char *);
  你的只能初始化,在不是初始化的地方最好还是用assign().
  3,CString -> string
  string s(CString.GetBuffer());
  GetBuffer()后一定要ReleaseBuffer(),否则就没有释放缓冲区所占的空间.
  
  
  《C++标准函数库》中说的
  有三个函数可以将字符串的内容转换为字符数组和C—string
  1.data(),返回没有”/0“的字符串数组
  2,c_str(),返回有”/0“的字符串数组
  3,copy() 

 

 

第二部分为Unicode环境下,VS2005调试环境

 

Cstring to char *

 

Cstring sSql=_T("hello world");

char * psText=new char[sSql.GetLength()*2];

wsprintfA(psText,"%ls",sSql);

delete pstext;

 

 

 

char * Unicode2ASCII(wchar_t * wSrc)

{

 

 

DWORD dwNum = WideCharToMultiByte(CP_OEMCP,NULL,wSrc,-1,NULL,0,NULL,FALSE);

char *psText;

psText = new char[dwNum];

if(!psText)

{

delete []psText;

}

WideCharToMultiByte (CP_OEMCP,NULL,wSrc,-1,psText,dwNum,NULL,FALSE);

return psText;

}

wchar_t* ASCII2Unicode(char * Src)

{

wchar_t   *wszData=new   wchar_t[strlen(Src)+1];   

MultiByteToWideChar(CP_ACP,MB_PRECOMPOSED,Src,-1,wszData,strlen(Src)+1);   

return wszData;

}

 

 

你可能感兴趣的:(Cstring,char*,string 转换)