C++中字符串怎么连接
时间: 2023-05-11 17:06:44 浏览: 61
在 C 中,可以使用 strcat() 函数将两个字符串连接起来。例如:
char str1[20] = "Hello";
char str2[20] = "World";
strcat(str1, str2);
这样,str1 的值就变成了 "HelloWorld"。
相关问题
c++ string字符串连接
在C++中,可以使用 `+` 运算符或者 `append()` 函数来进行字符串的连接操作。
使用 `+` 运算符进行字符串连接:
```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;
return 0;
}
```
使用 `append()` 函数进行字符串连接:
```cpp
#include <iostream>
#include <string>
int main() {
std::string str1 = "Hello, ";
std::string str2 = "world!";
str1.append(str2);
std::cout << str1 << std::endl;
return 0;
}
```
无论是使用 `+` 运算符还是 `append()` 函数,都可以将两个字符串连接在一起,并将结果存储在新的字符串变量中。以上示例中,输出结果都是 `"Hello, world!"`。
需要注意的是,`+` 运算符和 `append()` 函数在每次连接时都会创建一个新的字符串对象。如果需要频繁进行字符串连接操作,建议使用 `append()` 函数,因为它具有更好的性能。
c++字符串连接string函数
C++中的字符串连接函数是`std::string`类的成员函数`append()`或`+=`操作符。这些函数可以用于将一个字符串连接到另一个字符串的末尾。
使用`append()`函数,可以将一个字符串连接到另一个字符串的末尾。例如:
```cpp
std::string str1 = "Hello";
std::string str2 = " World";
str1.append(str2); // 将str2连接到str1的末尾
```
使用`+=`操作符,也可以实现相同的效果:
```cpp
std::string str1 = "Hello";
std::string str2 = " World";
str1 += str2; // 将str2连接到str1的末尾
```
以上两种方法都会将`str2`连接到`str1`的末尾,最终结果为`"Hello World"`。