CString::Find(),Delete(),Left(),Right(),Mid(),FindOneOf(),ReverseFind()
CString截取字串方法( 链接 ) ————————————以下为原文—————————————— 在CString中有 Find(),Delete(),Left(),Right(),Mid()就可以实现分离子串的目的了。 int Find( TCHAR ch ) const; 找到给定的字符返回它在字符串中对应的索引号;没有找到就返回-1。示例如下:
CString s( "abcd" ); ASSERT( s.Find( 'b' ) == 1 );
FindOneOf()
给定一字符串,然后查找其中出现的第一个字符位置,示例如下:
CString s( "abcdef" ); ASSERT( s.FindOneOf( "zb" ) == 1 );返回值:
- 如果查到,返回以0索引起始的位置
- 未查到,返回-1
ReverseFind()
该函数反向查找字符出现的位置。示例如下:
CString s( "abcd" ); ASSERT( s.ReverseFind( 'b' ) == 2 );
返回值:
- 如果查到,返回以0索引起始的位置
- 未查到,返回-1
CString Mid( int nFirst, int nCount ) const; nCount代表要提取的字符数, nFirst代表要提取的开始索引位置 CString Right( int nCount ) const; 返回的字符串是后nCount个字符。 Left()、Mid()、Right()函数示例如下:
CString s="天缘博客";//_T("天缘博客") CString s1=s.Left(3);//天? CString s2=s.Mid(3);//?博客 CString s4=s.Right(3);//?客s="123456789"; s1=s.Left(3); //123 s2=s.Mid(3); //456789 s4=s.Right(3); //789简例: CStringstr(”MyNameIsRenZheng”); CStringstr1, str2, str3; intx,y; x=str.Find(_T("N")); //2 y=str.Delete(0,5); // 16 str1 =str.Left(3); // MyN str2 =str.Mid(11, 4); //Zhen。注意,第二个参数是代表子串的长度 str3 =str.Right(3); // eng 假使有CString str=_T("My name is Ren Zheng"); 按空格提取子串可以采用如下方法: CStringstr=_T("My name is Ren Zheng"); CArray<CString,CString>strArray; //定义一个CString类型的动态数组,用来存取CString类型对象。 while(str.Find(_T(" "))+1)//当找不到空格时返回-1,所以这里我用它返回值加1来循环 { strArray.Add(str.Left(str.Find(_T(“”))));//找到空格的索引,截取空格左边的字符串,并将它添加到strArray动态数组中。 str.Delete(0,str1. GetLength_r()+1);//返回删除空格和其左边的字符串的得到的新字符串。 } strArray.Add(str);//最后加上经过最终删除后剩下的字符串; 这样按空格分离出的子串就都存储在动态CString类型的数组对象strArray中去了,现在就可以用strArray. Get_r(i)来得到每个子串。
发布评论