Cstring中的 Find()、Mid()、Replace() 用法

来源:互联网 发布:网络教育 高起专 时间 编辑:程序博客网 时间:2024/04/24 12:57

1、  CString::Find    

在一个较大的字符串中查找字符或子字符串 ,返回此CString对象中与需要的子字符串或字符匹配的第一个字符的从零开始的索引;如果没有找到子字符串或字符则返回-1。

[cpp] view plain copy
  1. int Find( TCHAR ch ) const;     
[cpp] view plain copy
  1. int Find( LPCTSTR lpszSub ) const;     
[cpp] view plain copy
  1. int Find( TCHAR ch, int nStart ) const;     
[cpp] view plain copy
  1. int Find( LPCTSTR pstr, int nStart ) const;  

其中,nStart 字符串中开始搜索的字符的索引,如果是0,则是从头开始搜索。如果nStart不是0,则位于nStart之前的字符不包括在搜索之内,但是会包括nStart处的字符。
 

[cpp] view plain copy
  1. CString s( "abcdef" );   int n = s.Find( 'c' ); // 结果 n = 2   int f = s.Find( "de" ) ; // 结果 f = 3   

[cpp] view plain copy
  1. CString str("The stars are aligned");   int n = str.Find('e',2); //结果 n = 2  

 

2、CString::Mid

 CString Mid( int nFirst, int nCount ) const;

此成员函数从此CString对象中提取一个长度为nCount个字符的子串,从nFirst(从零开始的索引)指定的位置开始。此函数返回一个对所提取的字符串的拷贝,可能是空的。

     nFirst 此CString对象中的要被提取的子串的第一个字符的从零开始的索引。

 nCount 要从此CString对象中提取的字符数。如果没有提供这个参数,则字符串的其余部分都被提取。

[cpp] view plain copy
  1. CString s( _T("abcdef") );   ASSERT( s.Mid( 2, 3 ) == _T("cde") );   


 

[cpp] view plain copy
  1. CString strBuff(buff);    //将buff由char*型转换为CString型.内容为0,0,1,1,4  
  2. int pos1=0,pos2=0;  
  3. pos2 = strBuff.Find(",",pos1);  
  4. if (pos2==-1) return FAULSE;  
  5. m_screenmode.screen_info[j].x = atoi(strBuff.Mid(pos1,pos2-pos1));  

上面的代码通过Find()和Mid()来获取逗号之间的内容,依次类推,不断变化pos1和pos2的值,就可以将每个逗号间的值全都取出来。

3、CString::Replace

  int Replace( TCHAR chOld, TCHAR chNew );

  int Replace( LPCTSTR lpszOld, LPCTSTR lpszNew );

在替换之后,该字符串有可能增长或缩短;那是因为lpszNew和lpszOld的长度不需要是相等的。两种版本形式都进行区分大小写的匹配。

0 0
原创粉丝点击