1. string类的operator+=/append/push_back
1.1 std::string::operator+=
- 原型:string& operator+= (const string& str);
- 说明:把string型字符串str连接到源字符串的结尾。
- 原型:string& operator+= (const char* s);
- 说明:把char型字符串s连接到源字符串的结尾。
- 原型:string& operator+= (char c);
- 说明:把字符c连接到源字符串的结尾。
- 原型:string& operator+= (initializer_list il);
- 说明: An initializer_list object.These objects are automatically constructed from initializer list declarators.The characters are appended to the string, in the same order.
代码示例:
#include <iostream> #include <string> using namespace std; int main () { string name ("John"); string family ("Smith"); name += " K. "; // c-string name += family; // string name += '\n'; // character cout<<name; system("pause"); return 0; } =>John K. Smith
1.2 std::string::append
- 原型:string& append (const string& str);
- 说明:把string型字符串str连接到源字符串结尾。
- 原型:string& append (const string& str, size_t subpos, size_t sublen = npos);
- 说明:用string型字符串str中从下标为subpos处开始的sublen长度的字符串连接到当前字符串结尾。
- 原型:string& append (const char* s);
- 说明:把char型字符串s连接到当前字符串结尾。
- 原型:string& append (const char* s, size_t n);
- 说明:用char型字符串s开始的n个字符连接到当前字符串结尾。
- 原型:string& append(size_t n, char c);
- 说明:在当前字符串结尾添加n个字符c。
- 原型:template < class InputIterator> string& append(InputIterator first, InputIterator last);
- 说明: Appends a copy of the sequence of characters in the range [first,last), in the same order.
- 原型:string& append(initializer_list il);
- 说明: Appends a copy of each of the characters in il, in the same order.
代码示例:
#include <iostream> #include <string> using namespace std; int main () { string str; string str2="Writing "; string str3="print 10 and then 5 more"; // used in the same order as described above: str.append(str2); // "Writing " str.append(str3, 6, 3); // "10 " str.append("dots are cool", 5); // "dots " str.append("here: "); // "here: " str.append(10u, '.'); // ".........." str.append(str3.begin()+8, str3.end()); // " and then 5 more" str.append<int>(5, 0x2E); // "....." cout<<str<<endl; system("pause"); return 0; } =>Writing 10 dots here: .......... and then 5 more.....
1.3 std::string::push_back
- 原型:void push_back (char c);
- 说明:添加字符到字符串的末尾。
代码示例:
#include <iostream> #include <string> using namespace std; int main () { string str = "hello world"; str.push_back('!'); cout<<str<<endl; system("pause"); return 0; } =>hello world!
参考文献:
[1] 网络资源: http://www.cplusplus.com/reference/string/string/string/