在 C++ 中,我们对 string 字符串进行追加,我们可以使用 append 函数。
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;
}
程序运行后,控制台输出如下:
我们使用了字符串的 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;
}
程序运行后,控制台输出如下:
我们使用了字符串的 append 函数,实现了字符串的追加。
在 C++ 中,我们对 string 字符串进行追加,我们可以使用 append 函数。