预备知识:
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 <<endl;
/*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.