参考地址:https://learn.microsoft.com/zh-cn/cpp/atl-mfc-shared/reference/cstringt-class?view=msvc-170
CString 类在 MFC(Microsoft Foundation Classes)中提供了丰富的成员函数来操作和处理字符串。以下是一些主要的 CString 成员函数及其描述和用法示例:
构造函数和赋值
CString():默认构造函数,创建一个空的CString对象。CString(const CString& stringSrc):拷贝构造函数,通过另一个CString对象初始化。CString(LPCTSTR lpsz):通过 C 风格的字符串初始化。CString& operator=(const CString& stringSrc):赋值操作符,将一个CString对象赋值给另一个。
长度和容量
int GetLength() const:返回字符串的长度(不包括终止字符)。BOOL IsEmpty() const:检查字符串是否为空。void SetLength(int nNewLength):设置字符串的长度。void Empty():清空字符串。
访问元素
TCHAR GetAt(int i) const:返回指定位置的字符。void SetAt(int i, TCHAR ch):设置指定位置的字符。
比较
int Compare(const CString& string) const:比较两个CString对象。int CompareNoCase(const CString& string) const:不区分大小写地比较两个CString对象。int Collate(const CString& string) const:使用区域设置信息比较两个CString对象。
连接和追加
CString& operator+=(const CString& string):将一个CString追加到当前字符串。CString& Append(const CString& string):追加一个CString到当前字符串。CString& AppendFormat(LPCTSTR format, ...):使用格式化字符串追加内容。
查找
int Find(TCHAR ch, int start = 0) const:查找指定字符在字符串中的位置。int Find(const CString& substring, int start = 0) const:查找子串在字符串中的位置。int ReverseFind(TCHAR ch) const:从字符串末尾开始查找指定字符。
替换
int Replace(TCHAR oldChar, TCHAR newChar):替换字符串中的所有指定字符。int Replace(const CString& oldSubstring, const CString& newSubstring):替换字符串中的所有指定子串。
转换
LPCTSTR GetBuffer(int nMinBufLength = -1):获取指向字符串内部缓冲区的指针。void ReleaseBuffer(int nNewLength = -1):释放通过GetBuffer获取的缓冲区。BSTR AllocSysString():将CString转换为BSTR(用于 COM 编程)。
格式化
void Format(LPCTSTR formatString, ...):格式化字符串,类似于 C 标准库中的sprintf。
其他
BOOL LoadString(UINT nID):从应用程序的资源文件中加载字符串。void MakeUpper()和void MakeLower():将字符串转换为大写或小写。void TrimLeft(TCHAR chTarget = _T(' '))和void TrimRight(TCHAR chTarget = _T(' ')):去除字符串左侧或右侧的指定字符(默认为空格)。void Trim():去除字符串两侧的指定字符(默认为空格)。
使用示例
以下是一些 CString 成员函数的使用示例:
CString str(_T("Hello World"));// 获取字符串长度
int length = str.GetLength();// 比较字符串
if (str.Compare(_T("Hello World")) == 0) {// 字符串相同
}// 追加字符串
str.Append(_T("!"));// 查找子串位置
int pos = str.Find(_T("World"));// 替换子串
str.Replace(_T("World"), _T("MFC"));// 格式化字符串
int num = 123;
str.Format(_T("Number: %d"), num);// 转换为大写
str.MakeUpper();// 去除字符串两侧的空格
str.Trim();// 从资源文件中加载字符串(假设有一个ID为123的资源字符串)
if (str.LoadString(123)) {