문자열 변환

IT/Programming 2008. 11. 28. 11:35

TCHAR --> CString

CStirng sSring;
TCHAR sTString = _T("가나다");

sString.Format(_T(%s), sTString);


CString --> TCHAR

TCHAR * des = new TCHAR[sString.GetLength() + 1]; // 1은 NULL을 위한 여유공간
_tcscpy(des, NowSaving.GetBuffer(0));


CString → int
int형 = _ttoi(CString형);

int → CString

CString형.Format( _T("%d"), int형);  



================================================================================

String - > UTF - 8

char buffer[20];

WCHAR Unicode[20];

char UTF8code[20];
int nUnicodeSize = MultiByteToWideChar(CP_ACP, 0, lpID, strlen(lpID), Unicode, sizeof(Unicode));

int nUTF8codeSize =
    WideCharToMultiByte(CP_UTF8, 0, Unicode, nUnicodeSize, UTF8code, sizeofUTF8code), NULL, NULL);

nUnicodeSize = MultiByteToWideChar(CP_UTF8, 0, UTF8code, nUTF8codeSize, Unicode, sizeof(Unicode));

memcpy(buffer, UTF8code, nUTF8codeSize);

이렇게 하면 buffer에 UTF-8로 변환

UTF-8 - > Unicode

void CCPimFONEDevice::UTF82UNICODE(char * strSrc,wchar_t *strTarget)
{
  int nSize = MultiByteToWideChar(CP_UTF8, 0, strSrc ,  -1 , 0 , 0);
  MultiByteToWideChar(CP_UTF8, 0, strSrc ,  -1 , strTarget, nSize);
}


BSTR은 SysFreeString 로 반드시 메모리 해제......
=============================================================================================
BSTR -> THCHAR
void  CCPimFONEDevice::BSTR2TCHAR(TCHAR * ptchar, BSTR bstr)
{
 CComVariant vtIn;
 USES_CONVERSION;
 strcpy(ptchar, OLE2A(bstr));
}

TCHAR -> BSTR
void  CCPimFONEDevice::TCHAR2BSTR(TCHAR * ptchar, BSTR *bstr)
{
 CComVariant vtIn;
 USES_CONVERSION;
 vtIn = ptchar;
 *bstr = vtIn.bstrVal;


}

===============================================================================================

wchar --> BSTR
wchar m_pszCallID [50];
BSTR bstr;
bstr= SysAllocString(m_pszCallID)


if (bstr!= NULL)
 SysFreeString(bstr)

BSTR -->wchar
wcscpy(pszCallID , bstr);

if (bstr!= NULL)
 SysFreeString(bstr)
================================================================================================
CString --> BSTR

 CString sTemp;
 BSTR bstrStr = sTemp.AllocSysString();
if (bstrStr != NULL)
 SysFreeString(bstrStr )


BSTR --> CString
 #include <atlbase.h>

CString sTemp, sTemp2;
BSTR bstr;
sTemp= "가나다라..";
bstr = sTemp.AllocSysString();
CComBSTR bstTemp;
bstTemp = bstr;
sTemp2 = bstTemp.Copy();
bstTemp.Detach();
if (bstr != NULL)
 SysFreeString(bstr)

Or

char* lpszText;
char lpszName[ 256 ];
lpszText = _com_util::ConvertBSTRToString( bstr);
strcpy( lpszName, lpszText );
delete []lpszText;
sTemp2.format("%s", lpszName);
if (bstr != NULL)
 SysFreeString(bstr)

 TIP==========================================
CString strError((LPCSTR)IDS_ERROR_FAILED);
문자열 리소스의 아이디는 반드시 (LPCSTR)로 캐스팅해야 합니다.
AND