C++字符串拼接append()
时间: 2023-07-28 16:28:33 浏览: 133
在C++中,可以使用字符串的成员函数 `append()` 来进行字符串拼接,即将一个字符串连接到另一个字符串的末尾。可以使用以下代码进行字符串拼接:
```cpp
string str1 = "Hello";
string str2 = "World";
str1.append(str2);
```
在上述代码中,`append()` 函数将字符串 `str2` 拼接到字符串 `str1` 的末尾,执行后,`str1` 的内容变为 `"HelloWorld"`。
`append()` 函数还可以接受一个字符串和一个起始位置和长度作为参数,表示将另一个字符串的一部分连接到当前字符串的末尾。例如:
```cpp
string str1 = "Hello";
string str2 = "World";
str1.append(str2, 0, 3);
```
在上述代码中,`append()` 函数将字符串 `str2` 的前3个字符拼接到字符串 `str1` 的末尾,执行后,`str1` 的内容变为 `"HelloWor"`。
除了 `append()` 函数之外,还可以使用 `+` 运算符进行字符串拼接,例如:
```cpp
string str1 = "Hello";
string str2 = "World";
string str3 = str1 + str2;
```
在上述代码中,`+` 运算符将字符串 `str1` 和字符串 `str2` 进行拼接,并将结果赋值给字符串 `str3`,执行后,`str3` 的内容变为 `"HelloWorld"`。
阅读全文
相关推荐


















