最近做的程序与字符串处理密切相关,故在网上搜集了些CString的常用函数和范例
与大家共享
☆改变大小写:
CString::MakeUpper和CString::MakeLower两个成员函数(不带参数)能使整个字符串变成大/小写字母。
例: str1 = “hello”;
str1.MakeUpper();
afxDump << str1; // 输出结果是”HELLO”;
☆反转:void CString::MakeReverse();
☆从.rc文件读入字符串:
CString::LoadString函数把传入的字符串资源ID对应的字符串读入到CString对象中。如果成功就返回非零值。
BOOL bResult = LoadString(IDS_FILENOTFOUND
);
☆子串操作
→去掉字符串左边空格:str1.TrimLeft();
→去掉字符串右边空格:str1.TrimRight();
→获得指定位置字符:char a = str1.GetAt(3); 相应的有CString::SetAt函数,修改指定位置字符。
→删除字符串中所有指定字符:
str1 = “Hello test”;
str1.Remove(‘t’);
afxDump << str1; //输出”Hello es”;
→删除指定位置指定长度的子串:
str1 = “Hello test”;
str1.Delete(3, 2); //第一个参数为index(从零开始)
//第二个参数是长度
afxDump << str1; //输出”Hel test”;
→清空对象的内容:
void CString::Empty();
→查找子串:
※CString::Find函数有四个重载,可以进行字符和字串的搜索,同时还可以指定搜索的起始位置,并返回第一次查找到的index。
int Find( TCHAR ch ) const;
int Find( LPCTSTR lpszSub ) const;
int Find( TCHAR ch, int nStart ) const;
int Find( LPCTSTR pstr, int nStart ) const;
※CString::ReverseFind是返回字符串中最后一个匹配字符的index,与Find函数查找方向正好相反,可惜只有一种重载:
int ReverseFind( TCHAR ch ) const;
※CString::FindOneof查找的是第一个与指定字符串中任意一个匹配字符的index。(好像有点绕口,看看例子就明白了)
str1 = “Hello test”;
int j = str1.Find(“el”);
afxDump << “j=” << j << “/n”;
int k = str1.Find(‘e’, 3);
afxDump << “k=” << k << “/n”;
int l = str1.ReverseFind(‘t’);
afxDump << “l=” << l << “/n”;
int m = str1.ReverseFind(‘t’);
afxDump << “m=” << m << “/n”;
int n = str1. FindOneOf(“stuv”);
afxDump << “n=” << n << “/n”;
输出结果:
j=1
k=7
l=9
m=9
n=6
→字串截断:CString::Left、CString::Right函数都只带一个参数,并且都返回一个CString对象,作用是截取左/右边指定长度的子串。CString::Mid函数第一个参数指定位置,第二个参数指定长度。这几个都是常用的函数,就不写例子了
→获得Buffer
经常有人问到CString对象和char *的转换问题,除了前面说到的强制转化,就是用这个了
LPTSTR GetBufferSetLength( int nNewLength );使用返回的指针可以直接修改CString对象的内容,不过有两点要注意,一是如果指定长度比原CString长度短(截断)请记得在后面补’/ 0’ ,二是在调用CString对象的任何其它成员函数前请一定记得ReleaseBuffer,也许不用似乎并没有出错,但是说不定就是大隐患的根源。
→CString::SpanExcluding函数
以前回答过一个把CString对象分离子串的问题,现在想想,如果当时用这个函数的话,将使多么的方便。函数原型:
CString SpanExcluding( LPCTSTR lpszCharSet ) const;
它查找CString对象中与lpszCharSet串中任意匹配的第一个字符,并返回一个CString对象,该对象的内容是原来对象从起始位置到查找到字符的前一个字符的部分。这在分离用分割符(逗号空格之类)隔开的子串的时候将十分方便:
str1 = “Hello test”;
str2 = str1.SpanExcluding(“ ,”);
afxDump << str2; //输出”Hello”
同时,还有一个很方便的函数:CString::SpanIncluding,函数原型:
CString SpanIncluding( LPCTSTR lpszCharSet ) const;
它返回对象中前若干个字符,这些字符都必须在lpszCharSet之中:
str1 = “Hello test”;
str2 = str1.SpanIncluding(“ABCDEFGHIJK”);
afxDump << str2; //输出”H”
→插入子串:用CString::Insert可以插入字符或者字串到指定位置
str1 = “Hello test”;
str1.Insert(2,“ABCD”);
afxDump << str1; //输出”HeABCDllo test”
→替换:CString::Replace的作用是将原来对象中的所有匹配相替换指定字符/子串。有两个重载原型:
int Replace( TCHAR chOld, TCHAR chNew );
int Replace( LPCTSTR lpszOld, LPCTSTR lpszNew );
☆CString对象的属性操作:这些都很常用了,简要说明之
int GetLength( ) const; //获得buffer的长度
BOOL IsEmpty( ) const; //判断CString对象内容是否为空
int Compare( LPCTSTR lpsz ) const; //与lpsz按ASCII码比较
int CompareNoCase( LPCTSTR lpsz ) const; //与lpsz按ASCII码比较,忽略大小写
CString::Format /*用来格式化对象。切记不要把对象本身放到Format函数的参数中去了*/