14-用于追加和相加的方法
F.7.1 用于追加和相加的方法
可以使用重载的+ =运算符或append()方法将一个字符串追加到另一个字符串的后面。如果得到的字符串长于最大字符串长度,将引发length_error异常。+=运算符使得能够将string对象、字符串数组或单个字符追加到string对象的后面:
basic_string& operator+=(const basic_string& str);
basic_string& operator+=(const charT* s);
basic_string& operator+=(charT c);
append()方法也使得能够将string对象、字符串数组或单个字符追加到string对象的后面。此外,通过指定初始位置和追加的字符数,或者通过指定区间,还可以追加string对象的一部分。通过指定要使用字符串中的多少个字符,可以追加字符串的一部分。追加字符的版本使得能够指定要复制该字符的多少个实例。下面是各种append()方法的原型:
basic_string& append(const basic_string& str);
basic_string& append(const basic_string& str, size_type pos,
size_type n);
template<class InputIterator>
basic_string& append(InputIterator first, InputIterator last);
basic_string& append(const charT* s);
basic_string& append(const charT* s, size_type n);
basic_string& append(size_type n, charT c); // append n copies of c
void push_back(charT c); // appends 1 copy of c
下面是几个示例:
string test("The");
test.append("ory"); // test is "Theory"
test.append(3,'!'); // test is "Theory!!!"
operator+()函数被重载,以便能够拼接字符串。该重载函数不修改字符串,而是创建一个新的字符串,该字符串是通过将第二个字符串追加到第一个字符串后面得到的。加法函数不是成员函数,它们使得能够将string对象和string对象、string对象和字符串数组、字符串数组和string对象、string对象和字符以及字符和string对象相加。下面是一些例子:
string st1("red");
string st2("rain");
string st3 = st1 + "uce"; // st3 is "reduce"
string st4 = 't' + st2; // st4 is "train"
string st5 = st1 + st2; // st5 is "redrain"