C++字符串类中insert常见用法总结

本文详细解析了C++中字符串insert方法的多种用法,包括在指定位置插入字符、字符串及子字符串,通过实例展示了如何正确使用这些方法。

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

今天用到了insert其中的一个用法 在指定位置插入一个char,结果用的时候和用法中在指定位置插入string用混了。所以打算整理一下insert的常见用法,也让自己记忆更深刻一点。

1,
//basic_string& insert( size_type index, size_type count, CharT ch );
//在字符串中第index个位置插入count个字符‘ch’

string str1 = “hello”;
string str2 = str1.insert(0,2,‘x’);//在str1中第0个位置插入2个字符‘x’
cout<<str2<<endl; //xxhello

2,
//basic_string& insert( size_type index, const basic_string& str );
//在字符串第index位置插入一个string

string str1 = “hello”;
string str2= str1.insert(1,str1);//在字符串str1第1个位置插入str1
cout<<str2<<endl; //hhelloello

//basic_string& insert( size_type index, const CharT s );
//在index位置插入一串字符
*

string str1 = “hello”;
string str2= str1.insert(1,‘aaaa’);//在str1的第一个位置插入字符串‘aaaa’
cout<<str2<<endl; //haaaaello

3,
//basic_string& insert( size_type index, const CharT s, size_type count );
//在index位置插入字符串中的count个字符
*

string str1 = “hello”;
string str2= str1.insert(1,“word”,2);//在str1的第一个位置插入字符串’word’中的2个字符wo
cout<<str2<<endl; //hwoello

4,
//basic_string& insert( size_type index, const basic_string& str,size_type index_str, size_type count );
//在index位置插入常量str的从index_str开始的count个字符

string str1 = “hellobeijing”;
string str2 = “helloword”;
string str3= str2.insert(6,str1,3,3);//在str2的第六个位置插入str1的从3开始的3个字符‘lob’
cout<<sstr<<endl; //hellowlobord

5,
//void insert( iterator pos, size_type count, CharT ch );
//在迭代器指向的pos位置插入count个字符ch

string str1 = “hello”;
str1.insert(++str1.begin(),2,‘a’);
//在迭代器指向str1++(即从0开始第一个位置)位置插入2个字符’a’
cout<<str1<<endl; //haaello

感觉常用的就这些吧。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值