C++如何连接两个字符串s1和s2,给出append实现的代码
时间: 2024-02-12 07:09:03 浏览: 27
连接两个字符串s1和s2的方法可以使用string类的append函数,代码如下:
```cpp
#include <iostream>
#include <string>
using namespace std;
int main() {
string s1 = "Hello";
string s2 = "World";
s1.append(s2);
cout << s1 << endl;
return 0;
}
```
运行结果为:
```
HelloWorld
```
该代码将字符串s2连接到字符串s1的末尾,使用append函数实现。
相关问题
c++实现字符串拼接
C++中实现字符串拼接有多种方法,以下是两种常用的方法:
1.使用"+"运算符进行字符串拼接
```c++
#include <iostream>
#include <string>
using namespace std;
int main() {
string s1 = "hello ";
string s2 = "world";
string s3 = s1 + s2;
cout << s3 << endl; // 输出:hello world
return 0;
}
```
2.使用string类的append()函数进行字符串拼接
```c++
#include <iostream>
#include <string>
using namespace std;
int main() {
string s1 = "hello ";
string s2 = "world";
s1.append(s2);
cout << s1 << endl; // 输出:hello world
return 0;
}
```
c++ 字符串s,s1,s2,s1="12",s2="34"如何让s="123"?
可以使用字符串拼接的方式将s1和s2拼接到s上,可以使用C++中的+运算符或者使用字符串拼接函数`std::string::append`。
使用+运算符的方法如下:
```cpp
std::string s1 = "12";
std::string s2 = "34";
std::string s = s1 + s2;
```
使用`std::string::append`函数的方法如下:
```cpp
std::string s1 = "12";
std::string s2 = "34";
std::string s = s1;
s.append(s2);
```
无论是使用+运算符还是`std::string::append`函数,都可以实现将s1和s2拼接到s上,使得s的值为"123"。