CString对象的初始化:
CString s;
CString s1(_T("hello"));
TCHAR buffer[] = _T("hello");
CString s2 = buffer;
CString对象的基本操作
长度:GetLength();
CString s = _T("abcdef");
int len = s.GetLength(); // len = 6
清空字符串:Empty();
CString str(_T("abc"));
BOOL mEmpty = str.IsEmpty(); //判断字符串是否为空
str.Empty();
mEmpty = str.IsEmpty(); //mEmpty == TRUE
转换大小写:MakeUpper()、MakeLower()
CString s = _T("aBc");
s.MakeUpper() // s="ABC"
s.MakeLower() // s = "abc"
转换顺序:MakeReverse()
CString str(_T("123"));
str.MakeReverse(); //str == 321
字符串的比较:==、!=、(<、>、<=、>= )、Compare(区分大小写)、CompareNoCase(不区分大小写)
CString str1(_T("abc"));
CString str2 = _T("aBc");
if(str1 == str2){//不成立
}
if(str1.CompareNoCase(str2){//成立,
}
字符串的查找:Finde,ReverseFind
Find 从指定位置开始查找指定的字符或者字符串,返回其位置,找不到返回 -1;
举例:
CString str(_T("1234567"));
int idx = str.Find(_T("456"), 0); //idx 的值为3;
int idx = str.Find(_T("90"),0);//idx = -1;
ReverseFind 从字符串末尾开始查找指定的字符,返回其位置,找不到返回 -1,虽然是从后向前查找,但是位置为从开始算起;
CString str(_T("abcdefg"));
int idx = str.ReverseFind('e'); //idx 的值为 4
字符串的替换:Replace
Replace 替换 CString 对象中的指定的字符或者字符串,返回替换的个数,无匹配字符返回 0;
CString str(_T("1234003438900"));
int num = str.Replace('0', ' '); //str == "1234 34389 "
字符串的删除:Remove
Remove 删除 CString 对象中的指定字符,返回删除字符的个数,有多个时都会删除;
CString str(_T("1234,90,90"));
int num = str.Remove(','); //str == 12349090
字符串的删除:Delete(int i,int len)
Delete 删除 CString 对象中的指定位置的字符,返回处理后的字符串长度;
CString str(_T("abcd"));
int num = str.Delete(0, 3); //删掉前三个字符
str.Delete(str.GetLength()-4,3);//删掉后三个
字符串的提取:Left、Mid、Right
Left、Mid、Right 三个函数分别实现从 CString 对象的 左、中、右 进行字符串的提取操作;
CString str(_T("abcd"));
s = str.Left(3) // s = abc,相当于python 的str[0:3]
s = str.Right(3) // s = bcd,相当于python的str[-3:]
单个字符的修改:
GetAt、SetAt 可以获取与修改 CString 对象中的单个 TCHAR 类型字符:
CString str(_T("1234"));
str.SetAt(0, '9'); //str == 9234
TCHAR ch = str.GetAt(2); //ch == 2