CString的截取

来源:互联网 发布:律师事务所php源码 编辑:程序博客网 时间:2024/06/03 05:07

一、CString之Find()、FindOneOf()、ReverseFind()

此三个函数返回值均为整数int。

1、Find()

该函数从左侧0索引开始,查找第一个出现的字符位置,返回position。示例如下:

CString s( "abcd" );ASSERT( s.Find( 'b' ) == 1 );

返回值:

  • 如果查到,返回以0索引起始的位置
  • 未查到,返回-1

2、FindOneOf()

给定一字符串,然后查找其中出现的第一个字符位置,示例如下:

CString s( "abcdef" );ASSERT( s.FindOneOf( "zb" ) == 1 ); 

返回值:

  • 如果查到,返回以0索引起始的位置
  • 未查到,返回-1

3、ReverseFind()

该函数反向查找字符出现的位置。示例如下:

CString s( "abcd" );ASSERT( s.ReverseFind( 'b' ) == 2 );

返回值:

  • 如果查到,返回以0索引起始的位置
  • 未查到,返回-1

二、CString之Left()、Mid()、Right()

查找完成后,我们可能需要截取字符串。CString有如下几个字符串截取函数。

1、Left(int nCount)

该函数截取左侧nCount个字符,如果遇到双字节字符(下面Mid和Right同样理解),比如中文,则可能会截断乱码。因为nCount是按照字节计数的。

2、Mid(int nFirst)和Mid( int nFirst, int nCount)

Mid(int nFirst)函数截取从nFirst开始,直到字符串结束的字符串。

Mid( int nFirst, int nCount)函数则截取从nFirst开始,截取nCount个字节字符。

3、Right(int nCount)

该函数截取右侧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);//123s2=s.Mid(3);//456789s4=s.Right(3);//789
erase函数的原型如下:
(1)string& erase ( size_t pos = 0, size_t n = npos );
(2)iterator erase ( iterator position );
(3)iterator erase ( iterator first, iterator last );
也就是说有三种用法:
(1)erase(pos,n); 删除从pos开始的n个字符,比如erase(0,1)就是删除第一个字符
(2)erase(position);删除position处的一个字符(position是个string类型的迭代器)
(3)erase(first,last);删除从first到last之间的字符(first和last都是迭代器)
下面给你一个例子:
复制代码
#include <iostream>#include <string>using namespace std;int main (){  string str ("This is an example phrase.");  string::iterator it;  // 第(1)种用法  str.erase (10,8);  cout << str << endl;        // "This is an phrase."  // 第(2)种用法  it=str.begin()+9;  str.erase (it);  cout << str << endl;        // "This is a phrase."  // 第(3)种用法  str.erase (str.begin()+5, str.end()-7);  cout << str << endl;        // "This phrase."  return 0;}
复制代码

0 0
原创粉丝点击