zoukankan      html  css  js  c++  java
  • string::erase的使用心得

    string::erase的三种函数原形
    1、iterator erase(
    iterator _First, iterator _Last);
    2、iterator erase(iterator _It);
    3、basic_string& erase(size_type _Pos = 0,size_type _Count = npos);

    一般的对于需要删除字符串开始和结尾的空格的代码,经常为

     1 #include <iostream>
     2 #include <string>
     3 using namespace std;
     4 
     5 void main()
     6 {
     7     string strTest="Hello, world.";
     8 
     9     strTest.erase(0, strTest.find_first_not_of(' '));
    10     cout << "[" << strTest << "]" << endl;
    11 
    12     strTest.erase(strTest.find_last_not_of(' ')+1);
    13     cout << "[" << strTest << "]" << endl;
    14 }
     1 #include <iostream>
     2 #include <string>
     3 using namespace std;
     4 
     5 void main()
     6 {
     7     string strTest="   Hello, world.  ";
     8 
     9     strTest.erase(0, strTest.find_first_not_of(' '));
    10     cout << "[" << strTest << "]" << endl;
    11 
    12     strTest.erase(strTest.find_last_not_of(' ')+1);
    13     cout << "[" << strTest << "]" << endl;
    14 
    15     string strTest="Hello, world.";
    16 
    17     strTest.erase(0, strTest.find_first_not_of(' '));
    18     cout << "[" << strTest << "]" << endl;
    19 
    20     strTest.erase(strTest.find_last_not_of(' ')+1);
    21     cout << "[" << strTest << "]" << endl;
    22 }

    结论

    1、只有第3种函数原形被调用。

    2、凑巧的是,当 strTest.find_last_not_of(' ')返回 string::npos的时候,对其加1恰好不会引起任何的副作用。string::npos被定义为-1,所以当strTest.find_last_not_of(' ')返回-1的时候正好需要删除0个字符。这种巧合尽管缩短了代码,但是却导致不易被理解.

    3、size_type显然是从1开始计数的,既如果第一个字符就是目的字符,那么find_xxx函数返回1。

  • 相关阅读:
    supervisorctl的安装使用
    react应用多入口配置
    百度编辑器
    formData文件上传
    thymeleaf的内联th:inline(在javascript访问model中的数据)
    浅谈Object.prototype.toString.call()方法
    JS中call()和apply()以及bind()的区别
    Json对象与Json字符串的转化
    全面解析JavaScript中“&&”和“||”操作符(总结篇)
    TortoiseSVN客户端重新设置用户名和密码
  • 原文地址:https://www.cnblogs.com/lzjsky/p/1925493.html
Copyright © 2011-2022 走看看