二维码 短网址 cnBeta

C++函数CString类常用函数

C++ STL库里有很多与字符串操作相关的函数,熟练应用STL,字符串的处理将变得轻松、自在。

字符串截取函数:

1CString Left( int nCount ) const;    //从左边1开始获取前 nCount 个字符
2CString Mid( int nFirst ) const;    //从左边第 nCount+1 个字符开始,获取后面所有的字符
3CString Mid( int nFirst, int nCount ) const;    //从左边第 nFirst+1 个字符开始,获取后面  nCount 个字符
4CString Right( int nCount ) const;    //从右边1开始获取从右向左前 nCount 个字符

注:在函数后面加 const 的意思是:如果一个类声明了一个常量对象,这个对象只能使用后边带 const 这个的方法.

例:
 CString a,b;
 a = "123456789";
 b = a.Left(4);   //值为:1234
 b = a.Mid(3);    //值为:456789
 b = a.Mid(2, 4); //值为:3456
 b = a.Right(4);  //值为:6789

字符串小写转大写函数:

1void MakeUpper();    //这个函数可以将CString字符转化为一个大写的字符串。
例:
  // example for CString::MakeUpper
  CString s( "abc" );
  s.MakeUpper();
  ASSERT( s == "ABC" );

字符串查找函数:

1find()

查找第一次出现的目标字符串:

/*
* Author:  mybestwishes
* Created Time:  2011/4/9 15:56:44
* File Name: find.cpp
*/
#include <iostream>
#include <cstdio>
using namespace std;

int main(){
     string s1 = "abcdef" ; 
     string s2 = "de" ;
     int ans = s1.find(s2) ; //在s1中查找子串s2
     cout<<ans<<endl;
     system("pause");
}

说明:如果查找成功则输出查找到的第一个位置,否则返回-1 ;

查找从指定位置开始的第一次出现的目标字符串:

/*
* Author:  mybestwishes
* Created Time:  2011/4/9 15:56:44
* File Name: find.cpp
*/
#include <iostream>
#include <cstdio>
using namespace std;

int main(){
     string s1 = "adedef" ; 
     string s2 = "de" ;
     int ans = s1.find(s2,2) ; //从s1的第二个字符开始查找子串s2
     cout<<ans<<endl;
     system("pause");
}

2find_first_of()

查找子串中的某个字符最先出现的位置。find_first_of()不是全匹配,而find()是全匹配

/*
* Author:  mybestwishes
* Created Time:  2011/4/9 15:56:44
* File Name: find.cpp
*/
#include <iostream>
#include <cstdio>
using namespace std;

int main(){
     string s1 = "adedef" ; 
     string s2 = "dek" ;
     int ans = s1.find_first_of(s2) ; //从s1的第二个字符开始查找子串s2
     cout<<ans<<endl;
     system("pause");
}

其中find_first_of()也可以约定初始查找的位置:  s1.find_first_of(s2 , 2) ;

3find_last_of()

这个函数与find_first_of()功能差不多,只不过find_first_of()是从字符串的前面往后面搜索,而find_last_of()是从字符串的后面往前面搜索。可以自行测试一下。

4rfind()

反向查找字符串,即找到最后一个与子串匹配的位置。

5find_first_not_of()

找到第一个不与子串的位置。

 

参考:http://mawenhao19930620.blog.163.com/blog/static/12857536120113935636277/

   http://blog.sina.com.cn/s/blog_9d4b5dd601013k9e.html#commonComment

 

posted @ 2016-11-16 20:18  何苦而乐  阅读(610)  评论(0编辑  收藏  举报
返回顶部