C++字符串

C++字符串

  • 窄字节

    char、char*、 const char*
    CHAR、 (PCHAR、PSTR、LPSTR)、LPCSTR
    
  • Unicode宽字节

    wchar_t、 wchar_t*、 const wchar_t*
    WCHAR、 (PWCHAR、PWSTR、LPWSTR)、LPCWSTR
    
  • T 通用类型

    TCHAR、(TCHAR*、 PTCHAR、PTSTR、LPTSTR)、LPCTSTR
    

    其中:P代表指针的意思,STR代表字符串的意思,L是长指针的意思,在WIN32平台下可以忽略,C代表const常量的意思,W代表wide宽字节的意思,T理解为通用类型。就是根据项目中是否定义_UNICODE宏,有则表示宽字节编码,定义成wchar_t,否则就是窄字节编码,定义为char类型。

计算宽窄字符串字节

窄字符:strlen(p_str) + 1.

宽字符:(wcslen(p_str) + 1) * sizeof(wchar_t)

宽窄字节字符串的转换

WideCharToMultiByte实现宽字节转换到窄字节

MultiByteToWideChar实现窄字节转换到宽字节

示例:

//将单字节char*转化为宽字节wchar_t*  
int  AnsiToUnicode(const char* szStr, wchar_t *szStrDst)
{
	int nLen = MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, szStr, -1, NULL, 0);
	if (nLen == 0)
	{
		return nLen;
	}
	MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, szStr, -1, szStrDst, nLen);
	return nLen;
}
///宽字节wchar_t转为单字节
char* UnicodeToAnsi(const wchar_t* szStr)
{
	int nLen = WideCharToMultiByte(CP_ACP, 0, szStr, -1, NULL, 0, NULL, NULL);
	if (nLen == 0)
	{
		return NULL;
	}
	char* pResult = new char[nLen];
	WideCharToMultiByte(CP_ACP, 0, szStr, -1, pResult, nLen, NULL, NULL);
	return pResult;
}
原文地址:https://www.cnblogs.com/zzr-stdio/p/15250264.html