Chinaunix首页 | 论坛 | 博客
  • 博客访问: 116140
  • 博文数量: 29
  • 博客积分: 1215
  • 博客等级: 中尉
  • 技术积分: 305
  • 用 户 组: 普通用户
  • 注册时间: 2010-12-05 16:29
文章分类
文章存档

2010年(29)

我的朋友

分类: C/C++

2010-12-21 20:56:19

预备知识:
s.erase(pos,len):删除从下表pos开始的len个字符
s.insert(pos,n,c):在下标为pos的元素之前插入n个字符c
s.insert(p,begin,end):在迭代器p指向的元素之前插入迭代器begin和end标记范围内的所有元素
s.insert(pos,s2):在下标为pos的元素之前插入string对象s2的副本
s.insert(pos,s2,pos2,len):在下标为pos的元素之前插入s2中从下表pos2开始的len个字符
s.assign(cp,len):将cp所指向数组的前len个字符替换s
s.insert(pos,cp):在下标pos元素之前插入cp所指向的以空字符结束的字符串副本

下面通过一个程序来说明。

程序清单:

#include <iostream>
#include <string>

using namespace std;

int main(int argc,char *argv[])
{
    string s("Hello World!");
    string::iterator iter = s.begin();
    while(iter != s.end())
    {
        cout << *iter++ << " ";
    }
    cout<<endl;
    
    /*erase last six characters from s*/
    s.erase(s.size()-7,7);
    cout << s <<endl;
    
    /*insert three '!' at the end of s*/
    s.insert(s.size(),3,'!');
    cout << s << endl;
    
    string s1,s2;
    s1 = "I love you,";
    s2 = "Lucy!";
    
    /*the follows are three equivalent ways to insert all the characters
      from s1 at the beginning of s2*/

    /*the first method: insert iterator range before s2.begin*/
// s2.insert(s2.begin(),s1.begin(),s1.end());


// cout << s2 <

    
    /*the second method: insert copy of s1 before opsition 0 in s2*/
// s2.insert(0,s1);


// cout << s2 << endl;


    
    s2.insert(0,s1,0,s1.size());
    cout << s2 <<endl;
    
    char *cp = "The only girl i care about has gone away.";
    s2.assign(cp,13);
    cout << s2 << endl;
    
    s2.insert(s2.size(),cp+13);
    cout << s2<< endl;
    
    return 0;
}

程序执行结果:
H e l l o   W o r l d ! 
Hello
Hello!!!
I love you,Lucy!
The only girl
The only girl i care about has gone away.


阅读(2299) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~