C++ 字符串拼接

本文介绍了两种在C++中进行字符串拼接的方法:直接相加和使用成员函数append。直接相加是简单的字符串连接,而append方法允许更灵活的操作,如指定起始位置和长度进行拼接。示例代码展示了如何使用这些方法将字符串连接在一起。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

第一种方法直接是字符串之间相加

#include <iostream>
using namespace std;
#include <string>
int main()
{
   string s1 ="hello ";
   string s2 = "world";
   string s3 = s1+s2; 
   cout <<s3 <<endl;
}

第二种方法使用append

#include <iostream>
using namespace std;
#include <string>
int main()
{
   string s1 ="hello ";
   string s2 = "world";
   string s3 = s1.append(s2); 
   cout <<s3 <<endl;
}

append 可以设置参数 

例如 append(“s1”,3) 这就是把s1前三位拼接

例如下面的就是把adbc的前2位,也就是ab 拼接到s1 上面

#include <iostream>
using namespace std;
#include <string>
int main()
{
   string s1 ="hello ";
   string s2 = "world";
   string s3 = s1.append("abcd",2); 
   cout <<s3 <<endl;
}

打印结果 

 append(s1,2,4)设置2个参数,就是从第2位开始后面的四位拼接

下面的就是abcdefg从第二位开始后面四位拼接到s1上面

#include <iostream>
using namespace std;
#include <string>
int main()
{
   string s1 ="hello ";
   string s2 = "world";
   string s3 = s1.append("abcdefg",2,4); 
   cout <<s3 <<endl;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值