C++ string 中的find,erase ,字符串截取 substr ,插入 insert

 find函数的变形较多。感觉会用   .find()    寻找单个字符首次出现的位置,或者字符串首次出现的位置就够了。

    string::size_type index;
    string a = "abcdef";
    string b = "def";
    index = a.find(b);
    if(index != string::npos)  ///则代表在 a 中找到了 b, index是b在a中首次出现的首个字母的下标
                               ///如此处 index 的值为  3
    if(index == string::npos)  ///表示未找到

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都是迭代器)

截取:

str.substr(begin,lenth)   // begin表示起始下标, lenth表示你要截取的长度.

string x = "abcdefg";
string s = x.substr(0,3);
// s 为 abc

插入函数:常用的,其它需求都可以配合substr使用

  std::string s1 = "gugugu",s2 = "miaomiao";
  s1.insert(3,s2);      /// insert(pos,string),在下标为pos处插入串
  s1.insert(0,1,'y');   /// 在下标为0处插入单个字符

 

你可能感兴趣的:(C++ string 中的find,erase ,字符串截取 substr ,插入 insert)