c++ string 连接
时间: 2024-02-29 08:50:34 浏览: 35
在C++中,可以使用"+"运算符或者使用string类的成员函数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(" ");
str1.append(str2);
std::cout << str1 << std::endl;
return 0;
}
```
以上两种方法都可以实现字符串的连接,输出结果都是"Hello World"。
相关问题
string连接 c++
在 C 语言中,可以使用 strcat 函数来连接字符串。这个函数的原型如下:
```c
char *strcat(char *dest, const char *src);
```
其中,dest 是目标字符串,src 是要追加的字符串。使用该函数时,它会将 src 追加到 dest 的末尾,并返回结果字符串的指针。
以下是一个使用 strcat 连接字符串的示例:
```c
#include <stdio.h>
#include <string.h>
int main() {
char str1[20] = "Hello";
char str2[] = "World";
strcat(str1, str2);
printf("Concatenated string: %s\n", str1);
return 0;
}
```
运行结果将输出 "HelloWorld"。注意,使用 strcat 函数时,确保目标字符串 dest 有足够的空间来容纳要追加的字符串 src。
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()` 函数,因为它具有更好的性能。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)