String 字符串连接
时间: 2024-05-09 19:11:23 浏览: 12
字符串连接是指将多个字符串拼接在一起形成一个新的字符串。在C++中,可以使用"+"运算符或者使用字符串类的成员函数来实现字符串连接。
使用"+"运算符进行字符串连接的示例代码如下:
```cpp
#include <iostream>
#include <string>
int main() {
std::string str1 = "Hello";
std::string str2 = "World";
std::string result = str1 + " " + str2; // 使用"+"运算符进行字符串连接
std::cout << result << std::endl; // 输出:Hello World
return 0;
}
```
另外,C++中的字符串类`std::string`还提供了成员函数`append()`和`+=`运算符,可以用于字符串连接。示例代码如下:
```cpp
#include <iostream>
#include <string>
int main() {
std::string str1 = "Hello";
std::string str2 = "World";
str1.append(" "); // 在str1后追加空格
str1.append(str2); // 在str1后追加str2
std::cout << str1 << std::endl; // 输出:Hello World
return 0;
}
```