C++字符串追加

C++字符串追加教程

C++ 中,我们对 string 字符串进行追加,我们可以使用 append 函数。

C++字符串追加详解

语法

string s1("123"), s2("abc"); s1.append(s2); // s1 = "123abc" s1.append(s2, 1, 2); // s1 = "123abcbc" s1.append(3, 'H'); // s1 = "123abcbcKKK" s1.append("ABCDE", 2, 3); // s1 = "123abcbcKKKCDE",添加 "ABCDE" 的子串(2, 3)

返回值

append 成员函数返回对象自身的引用。

说明

我们使用了字符串 append 的四种方法实现了对字符串的追加操作。

案例

追加字符串

使用 append 实现字符串的追加

#include <iostream> using namespace std; int main() { cout << "嗨客网(www.haicoder.net)\n" << endl; string s1 = "Hello"; string s2 = " HaiCoder"; string s = s1.append(s2); cout << "append s = " << s << ", s1 = " << s1 << endl; }

程序运行后,控制台输出如下:

08_C字符串string追加append.png

我们使用了字符串的 append 函数,实现了字符串的追加。

追加字符串

使用 append 实现字符串的追加

#include <iostream> using namespace std; int main() { cout << "嗨客网(www.haicoder.net)\n" << endl; string s1 = "Hello"; string s2 = " HaiCoder"; s1.append(s2, 1, 2); cout << "append s1 = " << s1 << endl; s1.append(3, 'H'); cout << "append s1 = " << s1 << endl; s1.append("ABCDE", 2, 3); cout << "append s1 = " << s1 << endl; }

程序运行后,控制台输出如下:

09_C字符串string追加append.png

我们使用了字符串的 append 函数,实现了字符串的追加。

C++字符串追加总结

在 C++ 中,我们对 string 字符串进行追加,我们可以使用 append 函数。