码迷,mamicode.com
首页 > 编程语言 > 详细

C++字符串处理函数

时间:2015-07-03 18:57:45      阅读:150      评论:0      收藏:0      [点我收藏+]

标签:

string 类提供字符串处理函数,利用这些函数,可以在字符串内查找字符,提取连续字符序列(称为子串),以及在字符串中删除和添加。我们将介绍一些主要函数。

1.find_first_of()和find_last_of()

函数find_first_of()和 find_last_of() 执行简单的模式匹配,如在字符串中查找单个字符c。函数find_first_of() 查找在字符串中第1个出现的字符c,而函数find_last_of()查找最后一个出现的c。返回值是匹配的位置。如果没有匹配发生,则函数返回-1。
  
int find_first_of(char c, int start = 0):
查找字符串中第1个出现的c,由位置start开始。 如果有匹配,则返回匹配位置;否则,返回-1.默认情况下,start为0,函数搜索整个字符串。
        
int find_last_of(char c):
查找字符串中最后一个出现的c。有匹配,则返回匹配位置;否则返回-1.该搜索在字符末尾查找匹配,所以没有提供起始位置。

 

例程:

   string str = "Mississippi";
     int index;
     // ‘s ‘ 在index 为 2、3、5、6处出现
     //SHIH:此处官方返回类型为string::size_type,其实是个整数,标准库类型将size_type定义为unsigned类型

  index = str.find_first_of(‘s‘,0);    // index为 2
     index = str.find_first_of(‘s‘,4);    // index为 5
     index = str.find_first_of(‘s‘,7);    // index为 -1,没有匹配
     // ‘s’的最后出现在 index= 6
     index = str.find_last_of(‘s‘);
     // while 循环输出每个‘i‘的index
     while((index = str.find_first_of(‘i‘, index))!= -1)
     {
        cout << "index" << index << " ";
        index++;   // restart search at next index
     }
    
   输出结果: index 7 index 10

 

 2.字符串中提取连续字符序列,即子串。

假定位置 start 和 字符数 count.   
string substr(int start=0,int count= -1);
从起始位置开始复制字符串中的count 个字符,并返回这些字符作为子串。如果字符串尾部小于count字符或者count 为-1,则字符串尾停止复制。如果不使用参数调用只包括位置start,则substr()返回从位置开始到字符串尾部的子串。find()函数在字符串中查找指定模式。该函数将字符串s和位置start作为参数,并查找s的匹配作为子串。     

int find(const string& s,int start = 0):
该搜索获得字符串s和位置start,并查找s的匹配作为子串。如果有匹配,则返回匹配的位置;否则返回-1。 默认情况下,start为0,函数搜索整个字符串。
      

例程:

  string fullname = "Mark Tompkin", firstname, lastname;
    int index;
   
    index = str.find_last_of(‘ ‘);   // index is 4
    // firstname = "Mark" lastname = "Tompkin"
    firstname = fullname.sub string(0,index);
    lastname = fullname.substring(index+1);
   
    index = fullname.find("kin");         // 在 index = 9 匹配 "Kin"
    index = fullname.find("omp",0);    // 在 index = 6 匹配 "omp"
    index = fullname.find("omp",7);    // index is -1 (无匹配)

 

C++字符串处理函数

标签:

原文地址:http://www.cnblogs.com/shih/p/4619364.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!