《白话C++》第10章 Page44 10.3 字符串处理 插入,删除,清除,替换

5.插入、删除、清除

(1)insert

用来在字符串指定位置插入字符,位置有两种表达,

一种是size_t类型,表示从0计起的字符串索引位子,

一种是迭代器位置

//在母串pos位置插入str, 原pos位置,及其后内容,均后移(下同)
string& insert(size_t pos, const string& str);


//在母串pos位置,插入str的子串
//子串为从str的subpos位置开始的sublen个字符,可以取npos
string& insert(size_t pos, const string& str
                , size_t subpos, size_t sublen);

//在母串pos位置, 插入C风格的字符串
//string& insert(size_t pos, const char* s);

//在母串pos位置,插入C风格的字符串,但最多插入n个字符
string& insert(size_t pos, const char* s, size_t n);

//在母串pos位置,插入n个字符c
string& insert(size_t pos, size_t n, char c)

//在母串的迭代器p的位置,插入n个字符c
void insert(iterator p, size_t n, char c);

//在母串的迭代器p的位置,插入1个字符c
iterator insert (iterator p, char c);

//在母串的迭代器p的位置,插入外部迭代器[first, last) 区间的内容
//注意first与last应是除母串之外的同一个容器的迭代器
template <class InputIterator>
void insert(iterator p, InputIterator first, InputIterator last);

(2)删除操作

//从pos起,删除len个字符,默认是删除全部字符
string& erase(size_t pos = 0, size_t len = npos);

//删除本串迭代器p位置的字符,
//返回删除之后新获得的迭代器位置
iterator erase(iterator p);

//删除本串迭代器[first~last)区间内的字符
iterator erase(iterator first, iterator last);

C++1还提供了pop_back()操作,用于删除最后一个字符,对应于push_back(c)操作

string str4 = "ABCDEFGH";
//删除最后一个字符,对应于push_back(c)操作
str4.pop_back();

(3)清空操作

void clear();

6.替换

std::string的替换操作,就像是删除操作与插入操作的合作

先将母串中指定范围的字符内容erase,然后再insert入指定子串的内容

//将母串pos, len限定范围的内容,替换为str
string& replace(size_t pos, size_t len, const string& str);

//同上,为C风格字符串版本
string& replace(size_t pos, size_t len, const char* s);
    
//将母串的迭代器[i1, i2)区间的内容,替换为str
string& replace(iterator i1, iterator i2, const string & str);

//同上,为C风格字符串版本
string& replace(iterator i1, iterator i2, const char* s);
    
//类上,但s最多取n个字符
string& replace(iterator i1, iterator i2, const char* s, size_t n);

//将母串pos, len限定范围的内容,
//替换为str的subpos, sublen限定的子串内容
string& replace(size_t pos, size_t len, const string& str
                            , size_t subpos, size_t sublen);

//类上,为C风格字符串版本
string& replace(size_t pos, size_t len, const char* s, size_t n);

//将母串pos开始的n个字符,全部替换为字符c
//下面的函数可能有错
//string& replace(size_t pos, size_t len, size_t n, char c);
string& replace(size_t pos, size_t n, char c);


//将母串[i1, i2)范围内的内容,全部替换为字符c
string& replace(iterator i1, iterator i2, size_t n, char c);

//将母串[i1, i2)范围内的内容,替换为[first, last)范围内的内容
//注意:[first, last)应来自母串之外的另一个容器
template <class InputIterator>
string& replace(iterator i1, iterator i2
                , InputIterator first, InputIterator last);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值