插入
向字符串中插入字符可以通过 insert() 函数完成。
string& string::insert (size_type index, const string& str)
string& string::insert (size_type index, const char* str)
- 这些函数可以将
str中的字符,插入到字符串索引index位置; - 这些函数都会返回
*this以便可以被链式调用; - 如果索引无效,则会抛出
out_of_range异常; - 如果结果超出最大字符个数则抛出
length_error异常; - 对于接受C风格字符串版本的函数,
str不能是NULL。
例子:
string sString("aaaa");
cout << sString << endl;
sString.insert(2, string("bbbb"));
cout << sString << endl;
sString.insert(4, "cccc");
cout << sString << endl;输出:
aaaa
aabbbbaa
aabbccccbbaa还有一个特别吓人的 insert()版本,使用它可以将一个子串插入到字符串的index位置:
string& string::insert (size_type index, const string& str, size_type startindex, size_type num)
- 该函数会将
str中从startindex开始的num个字符插入到字符串的index位置; - 这些函数都会返回
*this以便可以被链式调用; - 如果
index或者startindex,越界,则抛出out_of_range异常; - 如果结果超出最大字符个数则抛出
length_error异常;
例子:
string sString("aaaa");
const string sInsert("01234567");
sString.insert(2, sInsert, 3, 4); // insert substring of sInsert from index [3,7) into sString at index 2
cout << sString << endl;输出:
aa3456aa还有一个版本的 insert() 可以将C语言风格字符串的前面一部分插入到字符串中:
string& string::insert(size_type index, const char* str, size_type len)
- 将
str中的前len个字符插入到字符串中index位置; - 这些函数都会返回
*this以便可以被链式调用; - 如果索引无效,则抛出
out_of_range异常; - 如果结果超出最大字符个数则抛出
length_error异常; - 会忽略特殊字符 (例如
”)
例子:
string sString("aaaa");
sString.insert(2, "bcdef", 3);
cout << sString << endl;输出:
aabcdaa还有一个版本的 insert() 可以插入某个字符若干次:
string& string::insert(size_type index, size_type num, char c)
- 将字符
c在字符串index处插入num次; - 这些函数都会返回
*this以便可以被链式调用; - 如果索引无效,则抛出
out_of_range异常; - 如果结果超出最大字符个数则抛出
length_error异常;
例子:
string sString("aaaa");
sString.insert(2, 4, 'c');
cout << sString << endl;输出:
aaccccaa最后,还有三个版本的 insert() 用于配合迭代器使用:
void insert(iterator it, size_type num, char c)
iterator string::insert(iterator it, char c)
void string::insert(iterator it, InputIterator begin, InputIterator end)
- 第一个函数将字符
c在迭代器it前插入num次; - 第二个函数将字符c插入到迭代器
it前并返回一个指向该字符的迭代器; - 第三个函数将
[begin,end)范围内的字符插入到迭代器it前; - 如果结果超出最大字符个数则抛出
length_error异常;