MFC中CString类的介绍

1、CString类原型

template< typename BaseType, class StringTraits > 
class CStringT :  
public CSimpleStringT< BaseType,   
_CSTRING_IMPL_::_MFCDLLTraitsCheck< BaseType, StringTraits >::c_bIsMFCDLLTraits>

2、常见构造函数的使用

常用构造形式
CString( ) // 无参构造
CString( const CStringT& strSrc ) // 使用CString的引用作为参数构造
CString( const unsigned char* pszSrc ) // 使用const unsigned char *的指针变量构造
CString( char* pszSrc ) // 使用char *的指针变量构造
CString( unsigned char* pszSrc ) // 使用unsigned char *的指针变量构造
CString( wchar_t* pszSrc ) // 使用wchar_t *的指针变量构造(宽字符)
CString( char ch, int nLength = 1 ) // 使用char构造(窄字符)
CString( wchar_t ch, int nLength = 1 ) // 使用wchar_t构造(宽字符)
    
    
测试示例:    
CString s1;                     // Empty string
CString s2(_T("cat"));          // From a C string literal
CString s3 = s2;                // Copy constructor
CString s4(s2 + _T(" ") + s3);  // From a string expression
CString s5(_T('x'));             // s5 = "x"
CString s6(_T('x'), 6);          // s6 = "xxxxxx"
CString s7((LPCSTR)"help"); 	 // char * to CString
CString s8('a', 5);              // s8 = "aaaaa"

3、AppendFormat函数

(1)功能和调用方式类似C语言的sprintf+strcat函数

(2)函数原型

void __cdecl AppendFormat(
   PCXSTR pszFormat,
   [, argument]...
);
void __cdecl AppendFormat(
   UINT nFormatID,
   [, argument]...
);
参数:
pszFormat 需要格式化控制的字符串
nFormatID 包含格式控制字符串的字符串资源标识符(字符串表中的字符串ID号)
argument 可变参数列表

备注:
这个函数在CStringT中格式化并附加一系列字符和值。每个可选参数(如果有)都根据pszFormat中相应的格式规范或nFormatID标识的字符串资源进行转换和追加。

(3)调用示例

CAtlString str = _T("Some data:\t");
str.AppendFormat(_T("X value = %.2f\n"), 12345.12345);

4、Compare和CompareNoCase函数

(1)作用:比较两个CString对象是否相等(依赖于strcmp这一类的函数,比较规则依据ASCII码值大小,并且不受语言环境的影响)

(2)函数原型

// 区分大小写
int Compare(
   PCXSTR psz
) const;

// 不区分大小写
int CompareNoCase(
   PCXSTR psz
) const;

参数:
psz 需要比较的字符串,注意:源字符串是调用者

返回值:
	相等返回0
	小于0 则CString对象小于psz字符串
	大于0 则CString对象大于psz字符串

Compare函数备注:
	通用文本函数_tcscmp,它在TCHAR中定义。H,映射到strcmp、wcscmp或_mbscmp,具体取决于在编译时定义的字符集。每个函数对字符串执行区分大小写的比较,并且不受语言环境的影响。有关更多信息,请参见strcmp、wcscmp、_mbscmp。如果字符串包含内嵌的空值,为了进行比较,将认为在第一个内嵌的空字符处截断该字符串。

CompareNoCase函数备注:
	通用文本函数_tcscmp,它在TCHAR中定义。H,映射到strcmp、wcscmp或_mbscmp,具体取决于在编译时定义的字符集。每个函数对字符串执行不区分大小写的比较,并且不受语言环境的影响。有关更多信息,请参见strcmp、wcscmp、_mbscmp。如果字符串包含内嵌的空值,为了进行比较,将认为在第一个内嵌的空字符处截断该字符串。

(3)调用示例

CString str1 = _T("Hello");
CString str2 = _T("hello");
int nRes = str1.Compare(str2);
if (!nRes)
    AfxMessageBox(_T("the strings are identical."));
else if (nRes > 0)
    AfxMessageBox(_T("str1 is greater than str2."));
else
    AfxMessageBox(_T("str1 is less than str2."));

int nRes1 = str1.CompareNoCase(str2);
if (!nRes1)
    AfxMessageBox(_T("the strings are identical."));
else if (nRes1 > 0)
    AfxMessageBox(_T("str1 is greater than str2."));
else
    AfxMessageBox(_T("str1 is less than str2."));

5、Delete函数

(1)作用:从给定索引处的字符开始的字符串中删除一个或多个字符。

(2)函数原型

int Delete(
   int iIndex,
   int nCount = 1
);
参数:
iIndex 要删除的CStringT对象中第一个字符的从零开始的索引
nCount 要删除的字符数量

返回值:
	字符串改变后的长度

备注:
	如果nCount的长度大于字符串的长度,则会把要删除的第一个字符下标到字符串结尾的字符都删除。

(3)测试代码

CString str1 = _T("hello world the word");
str1.Delete(5, 3); // str1 = "hellorld the word"
int nLen = str1.Delete(5, 100); // str1 = "hello"

6、Find函数

(1)作用:在一个大字符串中查找一个字符或者子字符串(以第一个匹配的为准),默认从字符串首地址开始。

调用方式类似(strchr和strstr)。

(2)函数原型

int Find(
   PCXSTR pszSub,
   int iStart=0
) const;

int Find(
   XCHAR ch,
   int iStart=0
) const;
参数:
pszSub 需要查找的子字符串
iStart 查找的开始位置,默认是0,从字符串首元素开始
ch 需要查找的字符

返回值:
	返回值查找到的子串首元素或字符的位置(以大字符串的首地址开始算起);-1表示没找到。
	
备注:
	这个函数通过重载把strchr和strstr的功能进行了组合。

(3)调用示例

CString str1 = _T("abccdefgh123");
int nIndexch = str1.Find('c'); // nIndexch = 2;
nIndexch = str1.Find('c', 3); // nIndexch = 3;
int nIndexSubStr = str1.Find(_T("fgh")); // nIndexSubStr = 6;
nIndexSubStr = str1.Find(_T("fgdh")); // nIndexSubStr = -1;

7、FindOneOf函数

(1)作用:查找一串字符中的一个字符(以匹配到的第一个字符为准)

(2)函数原型

int FindOneOf(
   PCXSTR pszCharSet
) const;
参数:
pszCharSet 包含需要查找的字符合集的字符串

返回值:
	返回找到的第一个字符的位置(以大字符串的首元素为准),没找到返回-1

(3)调用示例

CString str1 = _T("abccdefgh123");
int nIndexch = str1.FindOneOf(_T("cdefg")); // nIndexch = 2;
nIndexch = str1.FindOneOf(_T("x1k")); // nIndexch = 9;
nIndexch = str1.FindOneOf(_T("xku")); // nIndexch = -1;

8、Format函数

(1)作用:格式化字符串,使用方法和sprintf一样

(2)函数原型

void __cdecl Format(
   UINT nFormatID,
   [, argument]...
);
void __cdecl Format(
   PCXSTR pszFormat,
   [, argument]...
);
参数:
nFormatID 包含格式控制字符串的字符串资源标识符。
pszFormat 格式控制字符串
argument 可选参数列表

备注:
	这个函数格式和存储一串字符和数字到CString对象中,每一个可选参数都会被转换并输出到对应的格式格式化字符串pszFormat中或者输出到指定字符串表ID的对象中。当把调用对象作为参数时,会发生不可预料的结果,导致函数调用失败。

(3)调用示例

CString str1;
str1.Format(_T("num = %d"), 15); // str1 = "num = 15"
str1.Format(IDS_STRING103, _T("hello")); // IDS_STRING103 = "%s"; str1 = "hello"
TCHAR s[] = _T("hello world");
str1.Format(_T("%s"), (LPCTSTR)s); // str1 = "hello world"

9、GetEnvironmentVariable函数

(1)作用:从调用进程的环境块中检索指定变量的值。该值的形式是一个以null结尾的字符串。

(2)函数原型

BOOL GetEnvironmentVariable(
   PCXSTR pszVar
);
参数:
pszVar 需要获取的环境变量名(以字符串形式)

返回值:
	成功获取返回非0;失败返回0

(3)调用示例

CString EnvStr;
EnvStr.GetEnvironmentVariable(_T("TEMP"));
_tprintf_s(_T("Current value of TEMP variable: %s\n"), EnvStr);

10、Insert函数

(1)作用:在指定位置插入一个字符或字符串

(2)函数原型

int Insert(
   int iIndex,
   PCXSTR psz
);
int Insert(
   int iIndex,
   XCHAR ch
);
参数:
	iIndex 插入的起始位置
	psz 待插入的子字符串
	ch 待插入的字符

返回值:
	返回插入后字符串的长度

备注:
	iIndex参数用于指定第一个字符或子串需要插入的位置;如果传入0,则将会在原字符串的首元素开始插入;如果传入的下标值超出最大的字符串下标值,则会把待插入的子串或字符进行拼接到原字符串的末尾。

(3)调用示例

CString str(_T("SoccerBest"));
int n = str.Insert(6, _T("is ")); // str = "Socceris Best"
ASSERT(n == str.GetLength()); // n = 13

str.Insert(6, _T(' ')); // str = "Soccer is Best"
str.Insert(55, _T('!')); // str = "Soccer is Best!"
str.Insert(55, _T("CESHI")); // str = "Soccer is Best!CESHI"

11、Left、Right、Mid函数

(1)作用:用于提取子字符串,Left从左边开始提取n个;Right从右边开始提取n个;Mid

(2)函数原型

CString Left(
   int nCount
) const;

CString Right(
   int nCount
) const;

CString Mid(
   int iFirst,
   int nCount
) const;

CString Mid(
   int iFirst
) const;
参数:
	nCout 表示需要提取的个数,也就是提取的边界
	iFirst 表示开始提取的位置(0~字符串长度)

返回值:
	返回一个CString对象
	
备注:
	nCount超出被提取字符串长度,则返回从首位置到末位置的子串;nCount<=0,返回空字符串

(3)调用示例

CString str1 = _T("hello123456");
CString lstr = str1.Left(5); // lstr = "hello"
lstr = str1.Left(20); // lstr = str1
lstr = str1.Left(-1); // lstr = NULL

CString rstr = str1.Right(5); // rstr = "23456"
rstr = str1.Right(20); // rstr = str1
rstr = str1.Right(0); // rstr = NULL

CString midstr = str1.Mid(3, 5); // midstr = "lo123"
midstr = str1.Mid(3, 88); // midstr = "lo123456"
midstr = str1.Mid(3, -1); // midstr = ""

12、MakeLower、MakeUpper、MakeReverse函数

(1)作用:转换字母的大小写及翻转字符串

(2)函数原型

CString& MakeLower(); // 全部字母转换为小写
CString& MakeUpper(); // 全部字母转换为大写
CString& MakeReverse(); // 翻转字符串

(3)调用示例

CString s(_T("abc"));
ASSERT(s.MakeUpper() == _T("ABC")); // TRUE
ASSERT(s.MakeLower() == _T("abc")); // TRUE
ASSERT(s.MakeReverse() == _T("cba")); // TRUE

13、Remove函数

(1)作用:移除字符串中指定的字符

(2)函数原型

int Remove(
   XCHAR chRemove
);
参数:
	chRemove 需要移除的字符

返回值:
	返回被移除的字符个数;0则说明原字符串没有被改动

备注:
	字符之间的比较方式是采用区分大小写的形式

(3)调用示例

CString str1 = _T("This is a test.");
ASSERT(str1.Remove(_T('t')) == 2); // str1 = "This is a es."

14、Replace函数

(1)作用:替换目标字符串中的某种字符或字符串

(2)函数原型

int Replace(
   PCXSTR pszOld,
   PCXSTR pszNew
);
int Replace(
   XCHAR chOld,
   XCHAR chNew
);
参数:
pszOld 指向一个以空字符结束的字符串,用于被新字符串替换
pszNew 指向一个以空字符结束的字符串,用于替换旧字符串
chOld 需要被替换的字符
chNew 新替换进去的字符

返回值:
	返回被替换的个数,如果返回0,表示没有替换。

备注:
	Replace可以更改字符串长度,因为pszNew和pszOld不必具有相同的长度,并且可以将旧子字符串的多个副本更改为新子字符串。该函数执行区分大小写的匹配。

(3)调用示例

CString strBang(_T("Everybody likes epee fencing"));
int n = strBang.Replace(_T("epee"), _T("foil"));
ASSERT(n == 1); // TRUE

15、SpanExcluding和SpanIncluding函数

(1)作用:从左边的第一个字符开始查找与给定串相等的字符,如果没有则返回空的串,反之,继续查找,到结束

SpanExcluding则相反,查找不匹配的;

(2)函数原型

CString SpanExcluding(
   PCXSTR pszCharSet
) const;

CStringT SpanIncluding(
   PCXSTR pszCharSet
) const;
参数:
	pszCharSet 需要提取或排除字符的组合

返回值:
	返回一个CString对象

备注:
SpanIncluding函数:
如果被提取字符串中的第一个字符不在pszCharSet中,则返回空字符串;否则返回一个连续的字符串。
	
SpanExcluding函数:
返回遇到pszCharSet参数中第一个字符前面的所有字符。如果没匹配到字符合集中的字符,则返回整个字符串。


常见用途:判断接收到的字符串是不是全为数字
BOOL IsDigital(CString str)
{
	return str==str.SpanIncluding("0123456789");
}

(3)调用示例

/* 在str中提取与strDigtal想等的串,从第一个'5’开始查找,....,
直到str中的一个字符在strDigtal找不到...,例子中,'9'条件不符,直接返回"51" 
*/
CString str;
CString strDigital("0123456");
str = "51920";
CString strVal = str.SpanIncluding(strDigital);
MessageBox(strVal); // strVal = "51"

// 查找到'6'的时候不匹配,返回"98"
str1 = "9867578";
CString strVal1 = str.SpanExcluding(strDigital);
MessageBox(strVal1); // strVal1 = "98"

16、Tokenize函数

(1)作用:分割字符串,使用多个分隔符(分隔符的顺序无关紧要)。

(2)函数原型

CString Tokenize(
   PCXSTR pszTokens,
   int& iStart
) const;
参数:
	pszTokens 分割符合集字符串
	iStart 分割的起始位置

返回值:
	CString对象

备注:
	Tokenize函数查找目标字符串中的下一个分隔符。psztoken中的字符集指定要找到的可能分隔符。在每次调用Tokenize函数时,函数从iStart开始,跳过前导分隔符,并返回一个包含当前标记的CStringT对象,该标记是下一个分隔符字符之前的字符串。iStart的值被更新为结束分隔符字符之后的位置,如果到达字符串的结尾,则更新为-1。通过一系列Tokenize调用,可以从目标字符串的其余部分中取出更多的标记,使用iStart跟踪字符串中下一个标记的读取位置。当没有更多的标记时,函数将返回一个空字符串,iStart将被设置为-1。

(3)调用示例

CAtlString str(_T("%First Second#Third"));
CAtlString resToken;
int curPos = 0;

resToken = str.Tokenize(_T("% #"), curPos);
while (resToken != _T(""))
{
    AfxMessageBox(resToken);
    resToken = str.Tokenize(_T("% #"), curPos);
}
/*
输出结果为:
第一次:First
第二次:Second
第三次:Third
*/

17、Trim函数

(1)作用:删除字符串两边缘中指定的字符

(2)函数原型

CStringT& Trim(
   XCHAR chTarget 
);
CStringT& Trim(
   PCXSTR pszTargets 
);
CStringT& Trim( );
参数:
chTarget 需要删除的目标字符

pszTargets 指向包含要裁剪的目标字符的字符串的指针。pszTarget中出现的所有前导字符和尾随字符都将从CStringT对象中删除。

(3)调用示例

CAtlString str;
str = _T("******Soccer is best!?!?!?!?!");

_tprintf_s(_T("Before: \"%s\"\n"), (LPCTSTR)str);
_tprintf_s(_T("After : \"%s\"\n"), (LPCTSTR)str.Trim(_T("?!*")));

// Output: 
// -------------------------- 
// Before: ******Soccer is best!?!?!?!?! 
// After: Soccer is best

18、TrimLeft和TrimRight

(1)作用:移除前导元素(TrimLeft)、移除

(2)函数原型

CStringT& TrimLeft(
   XCHAR chTarget 
);
CStringT& TrimLeft(
   PCXSTR pszTargets 
);
CStringT& TrimLeft( );

CStringT& TrimRight(
   XCHAR chTarget 
);
CStringT& TrimRight(
   PCXSTR pszTargets 
);
CStringT& TrimRight( );
参数:
chTarget 需要删除的目标字符
pszTargets 指向包含要裁剪的目标字符的字符串的指针。pszTarget中出现的所有前导字符和尾随字符都将从CStringT对象中删除。

返回值:
	CStringT对象

备注:
删除下列任一项的所有前导和尾随:
		由chTarget指定的字符。
		在pszTargets指定的字符串中找到的所有字符。
		空格。
		在TrimRight中空白符可以是换行符、空格或制表符。

(3)调用示例

/* TrimRight测试代码 */
	CString str = _T("    ****This a test code~~~@@@+++@@    @@");
	CString str2 = str.Trim(_T('@'));
	CString str1 = str.TrimRight(); // 移除空格

/* TrimLeft测试代码 */
	CString str = _T("    ****This a test code~~~@@@+++@@    @@");
	CString str1 = str.TrimLeft(); // 移除空格
	CString str2 = str.Trim(_T('*'));

猜你喜欢

转载自www.cnblogs.com/veis/p/12671022.html