// CString_Test.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include "atlstr.h"

int _tmain(int argc, _TCHAR* argv[])
{
	// 字符串的初始化
	CString testString1 = _T("This is a test");
	CString testString2 = testString1;
	CString testString3(_T("This is a test"));
	CString testString4(testString1);

	TCHAR szBuf[] = _T("This is a test");
	CString testString5 = szBuf;
	CString testString6(szBuf);

	TCHAR *p = _T("This is a test");
	CString testString7 = p;
	CString testString8(p);

	// 获取长度
	int nlen = testString8.GetLength();

	// 判断是否为空
	bool bFlag = testString8.IsEmpty();

	// 清空
	testString8.Empty();

	// 转换为大写
	testString7.MakeUpper();

	// 转换为小写
	testString7.MakeLower();

	// 转换顺序
	testString7.MakeReverse();

	// 连接
	testString8 = _T("aaa") + testString7 + szBuf;

	// 比较
	if (testString1 == testString2)
	{
		printf("相等");
	}

	return 0;
}



2、字符串的查找:

Find、ReverseFind、FindOneOf 三个函数可以实现字符串的查找操作
Find 从指定位置开始查找指定的字符或者字符串,返回其位置,找不到返回 -1;
举例:

CString str(_T("abcdefg"));
 int idx = str.Find(_T("cde"), 0); //idx 的值为2;




ReverseFind 从字符串末尾开始查找指定的字符,返回其位置,找不到返回 -1,虽然是从后向前查找,但是位置为从开始算起;

CString str(_T("abcdefg"));
 int idx = str.ReverseFind('e'); //idx 的值为4;




FindOneOf 查找参数中给定字符串中的任意字符,返回第一次出现的位置,找不到返回 -1;

CString str(_T("abcabcd"));
 int idx = str.FindOneOf(_T("cbd")); //idx 的值为1;



3、字符串的替换与删除:
Replace 替换 CString 对象中的指定的字符或者字符串,返回替换的个数,无匹配字符返回 0;

CString str(_T("abcdabc"));
 int num = str.Replace('b', 'k'); //str == akcdakc, num == 2



CString str(_T("abcdabc"));
 int num = str.Replace(_T("bc"), _T("kw")); //str == akwdakw, num == 2



Remove 删除 CString 对象中的指定字符,返回删除字符的个数,有多个时都会删除;

CString str(_T("abcdabcb"));
 int num = str.Remove('b'); //str == acdac, num == 3


Delete 删除 CString 对象中的指定位置的字符,返回处理后的字符串长度;

4、字符串的提取:
Left、Mid、Right 三个函数分别实现从 CString 对象的 左、中、右 进行字符串的提取操作;

CString str(_T("abcd"));
 CString strResult = str.Left(2); //strResult == ab
 strResult = str.Mid(1); //strResult == bcd
 strResult = str.Mid(0, 2); //strResult == ab
 strResult = str.Right(2); //strResult == cd
CString str(_T("abcd"));
 int num = str.Delete(1, 3); //str == a, num == 1


5、单个字符的修改:
GetAt、SetAt 可以获取与修改 CString 对象中的单个 TCHAR 类型字符;
[] 操作符也可以获取 CString 对象中的单个字符,但为只读的,不能进行修改;


CString str(_T("abcd"));
 str.SetAt(0, 'k'); //str == kbck
 TCHAR ch = str.GetAt(2); //ch == c

6、其他类型与 CString 对象类型的转换:
● 格式化字符串:Format 方法,实现从 int、long 等数值类型、TCHAR、TCHAR * 等类型向 CString 类型的转换;

int num = 6;
 CString str;
 str.Format(_T("%d"), num);




● CString 类型向 int 等数值类型、TCHAR * 类型的转换:


TCHAR *pszBuf = str.GetBuffer();
 str.ReleaseBuffer();


 TCHAR *p = (LPTSTR)(LPCTSTR)str;


 CString str1(_T("123"));
 int num = _ttoi(str1);

7、CString 对象的 Ansi 与 Unicode 转换:
大家可以直接使用前面文章的方法,此外这里给大家介绍一种从 Ansi 转换到 Unicode 的隐含方法:


//当前工程环境为Unicode
 CString str;
 str = "abc";
 char *p = "defg";
 str = p;

8、CString 对象字符串所占用的字节数:

CString str = _T("abc");
  错误的求法:sizeof(CString)、sizeof(str)
  正确的求法:str.GetLength()*sizeof(TCHAR)


 
当作为 TCHAR * 类型传参时,确保申请了足够用的空间,比如使用 GetModuleFileName 函数;