clear
清除全部内容
#include <cassert>
#include <string>
int main()
{
std::string s{ "Exemplar" };
std::string::size_type const capacity = s.capacity();
s.clear();
assert(s.capacity() == capacity);
assert(s.empty());
assert(s.size() == 0);
}
insert
插入字符
#include <cassert>//assert.h
#include <iterator>
#include <string>
using namespace std;
int main()
{
std::string s = "xmplr";
// insert(size_type index, size_type count, char ch)
s.insert(0, 1, 'E');//在0位置插入一个字符E
assert("Exmplr" == s);
// insert(size_type index, const char* s)
s.insert(2, "e");//在2位置插入字符e
assert("Exemplr" == s);
// insert(size_type index, string const& str)
s.insert(6, "a"s);//在6位置插入字符a
assert("Exemplar" == s);
// insert(size_type index, string const& str,
// size_type index_str, size_type count)
s.insert(8, " is an example string."s, 0, 14);//在8位置插入字符串[0-14)
assert("Exemplar is an example" == s);
// insert(const_iterator pos, char ch)
s.insert(s.cbegin() + s.find_first_of('n') + 1, ':');//在第一个n后面插入:
assert("Exemplar is an: example" == s);
// insert(const_iterator pos, size_type count, char ch)
s.insert(s.cbegin() + s.find_first_of(':') + 1, 2, '=');//在第一个:后面插入两个==
assert("Exemplar is an:== example" == s);
// insert(const_iterator pos, InputIt first, InputIt last)
{
std::string seq = " string";
s.insert(s.begin() + s.find_last_of('e') + 1,
std::begin(seq), std::end(seq));//在最后一个e后面插入seq
assert("Exemplar is an:== example string" == s);
}
// insert(const_iterator pos, std::initializer_list<char>)
s.insert(s.cbegin() + s.find_first_of('g') + 1, { '.' });//在第一个g后面插入.
assert("Exemplar is an:== example string." == s);
}
erase
移除字符
#include <iostream>
#include <algorithm>
#include <string>
int main()
{
std::string s = "This is an example";
std::cout << s << '\n';
s.erase(0, 5); // 擦除 "This "[0-5)
std::cout << s << '\n';//is an example
s.erase(std::find(s.begin(), s.end(), ' ')); // 擦除 ' '
std::cout << s << '\n';//isan example
s.erase(s.find(' ')); // 从 ' ' 到字符串尾裁剪
std::cout << s << '\n';//isan
}