第二章 字符和字符串处理

/*
1.编码格式
UTF-16:	将每个字符编码为2-4个字节
UTF-8:	将一些字节编码为1-4个字节,将0x0080以下的字符压缩为1字节,0x0080和0x07FF之间的字符转换为2个字节,0x0800以上的字符转换为3字节,最后,代理对被写为4字节
UTF-32:	将每个字符编码为4个字节


2.宽字符与宽字符串
wchar_t aValue[2] = {'a', 'b'};		//61 00 62 00
wchar_t* pWStr = L"Abc";			//41 00 62 00 63 00 00 00

TCHAR* pStr = TEXT("123");			//31 00 32 00 33 00 00 00	Unicode环境下
									//31 32 33 00				多字节环境下
									//在Unicode环境下,string无法直接由TCHAR*进行构造
									//在Unicode环境下,wstring可以由TCHAR*进行构造


3.使用TCHAR, TEXT替换项目中的非数据流的char和wchar,其能很好的搭配string,wstring		
#include <windows.h>
#ifdef UNICODE
typedef wstring m_string;
#else 
typedef string m_string;
#endif

m_string str = TEXT("SZN");			//不管是否是Unicode项目,此代码都可以通过编译	
									//使用上述方法,在MFC下,使用CString时候,也能很方便的进行和m_string的转换

#define _T(x)       __T(x)
#define _TEXT(x)    __T(x)


4.C运行库提供的字符串处理函数,常规的是str带头的,对于宽字节字符串,是以wcs替换str即可
wchar_t* wStr = L"123";
int nSize0 = wcslen(wStr);			//nSize0 = 3


5.使用_t开头的_s结尾的通用字符串安全处理函数
#include <tchar.h>
TCHAR* wStr = TEXT("123");
int nSize0 = _tcslen(wStr);			//nSize0 = 3	这个值不随是否是UNICODE环境所改变

tchar.h头文件中的一些定义				取决于是否定义了UNICODE
#define _tcscat		strcat
#define _tcscat_s	strcat_s
#define _tcscpy		strcpy
#define _tcscpy_s	strcpy_s
#define _tcslen		strlen
#define _tcsnlen	strnlen

#define _tcscat			wcscat
#define _tcscat_s		wcscat_s
#define _tcschr			wcschr
#define _tcscpy			wcscpy
#define _tcscpy_s		wcscpy_s
#define _tcscspn		wcscspn
#define _tcslen			wcslen
#define _tcsnlen		wcsnlen
#define _tcsncat		wcsncat
#define _tcsncat_s		wcsncat_s
#define _tcsncat_l		_wcsncat_l
#define _tcsncat_s_l	_wcsncat_s_l
#define _tcsncpy		wcsncpy
#define _tcsncpy_s		wcsncpy_s
#define _tcsncpy_l		_wcsncpy_l
#define _tcsncpy_s_l	_wcsncpy_s_l
#define _tcspbrk		wcspbrk
#define _tcsrchr		wcsrchr
#define _tcsspn			wcsspn
#define _tcsstr			wcsstr
#define _tcstok			wcstok
#define _tcstok_s		wcstok_s
#define _tcstok_l		_wcstok_l
#define _tcstok_s_l		_wcstok_s_l


6.多字节字符串转换为宽字节字符串
// #define CP_ACP                    0           // default to ANSI code page
// #define CP_OEMCP                  1           // default to OEM  code page
// #define CP_MACCP                  2           // default to MAC  code page
// #define CP_THREAD_ACP             3           // current thread's ANSI code page
// #define CP_SYMBOL                 42          // SYMBOL translations
// 
// #define CP_UTF7                   65000       // UTF-7 translation
// #define CP_UTF8                   65001       // UTF-8 translation

const WCHAR* pWStrC = L"123456";
char buff[1024] = {};
WideCharToMultiByte(CP_ACP, 0, pWStrC, wcslen(pWStrC), buff, 1024, nullptr, nullptr);	//buff = 0x003dfa20 "123456"

const char* pStrC = "123456";
WCHAR wBuff[1024] = {};
MultiByteToWideChar(CP_ACP, 0, pStrC, strlen(pStrC), wBuff, 1024);						//wBuff = 0x0040f0bc "123456"
*/

  

原文地址:https://www.cnblogs.com/szn409/p/7260816.html