1. 程式人生 > >C++字串之間轉化——多位元組字符集

C++字串之間轉化——多位元組字符集

一、字串之間轉化
1.string、char*與 const char*
<1>string->char*

    char *ctr = new char[str.length()+1];
    strcpy(ctr,str.c_str());
    delete[]ctr; //用完後釋放字串

<2>string->const char*

    string str("good");
    const char *p = str.c_str();//轉化成const char*

<3>char*->string

    char
*ctr = "good"; string str(ctr); //或 string str2 = ctr;

<4>char*->const char*

    char *ctr = "good";
    const char *ctr2 = ctr;

<5>const char*->string

    const char *ctr = "good";
    string str(ctr);

<6>const char*->char*

    const char *ctr = "good";
    char
*ctr2= new char[strlen(ctr)+1] ; strcpy(ctr2, ctr); delete[]ctr; //用完後釋放字串 //對於char[]可以用char *指向它,進而實現其它轉化

2.char* string 與CString
<1>char*->CString

    char *p = "good";

    CString cstr = p;
    //或
    CString cstr;
    cstr.Format("%s",p);

<2>string->CString

    string str
= "good"; CString cstr; cstr = str.c_str(); //或 cstr.Format("%s", str.c_str());

<3>CString->char*

    CString cstr = "good";
    char *p = cstr.GetBuffer(0);//讀取cstr內容
    cstr.ReleaseBuffer(); //後續對sctr有其他操作,要ReleaseBuffer
    //或
    char *p = (LPSTR)(LPCTSTR)cstr;

<4>CString->string

    CString cstr = "good";
    string str = cstr.GetBuffer(0);//讀取cstr內容
    cstr.ReleaseBuffer(); //後續對sctr有其他操作,要ReleaseBuffer
    //或
    string str = (LPSTR)(LPCTSTR)cstr;

二、數字與字串轉化
1.double與string
<1>double->string

    char temp[20];
    double a = 0.631;
    sprintf_s(temp, "%.2f", a);//保留2位小數
    string str =temp;

<2>string->double

    string a = "0.631";
    double b = atof(a.c_str());

2.double與char*
<1>double->char*

    char temp[20];
    double a = 0.631;
    sprintf_s(temp, "%.2f", a);//保留2位小數
    char *p = temp;

<2>char*->double

    char *a = "0.631";
    double b = atof(a);
//如果數字是int型,只需“%f”->"%d"、atof->atoi

3.double與CString
<1>double->CString

    double a = 0.631;
    CString cstr;
    cstr.Format("%.2f",a);

<2>CString->double

    CString cstr = "0.631";
    double a = atof(cstr);  
//如果數字是int型,只需“%f”->"%d"、atof->atoi