往string中插入字符串
时间: 2024-06-12 16:11:26 浏览: 16
往string中插入字符串可以使用insert函数,该函数有多种重载形式,可以插入不同类型的字符串或字符。以下是几种常用的insert函数的用法:
1. 在指定位置插入另一个string类型的字符串:
string s1 = "hello ";
string s2 = "world";
s1.insert(6, s2); // 在s1的第6个位置插入s2
// s1 = "hello world"
2. 在指定位置插入另一个string类型字符串的一部分:
string s1 = "hello ";
string s2 = "wide world";
s1.insert(6, s2, 5, 5); // 在s1的第6个位置插入s2从第5个位置开始的5个字符
// s1 = "hello world"
3. 在指定位置插入一个C-string类型的字符串:
string s1 = "hello ";
const char* c = "world";
s1.insert(6, c); // 在s1的第6个位置插入c类型字符串
// s1 = "hello world"
4. 在指定位置插入一个C-string类型字符串的一部分:
string s1 = "hello ";
const char* c = "wide world";
s1.insert(6, c, 5); // 在s1的第6个位置插入c类型字符串的前5个字符
// s1 = "hello world"
5. 在指定位置插入多个相同的字符:
string s1 = "hello ";
s1.insert(6, 3, '!'); // 在s1的第6个位置插入3个字符!
// s1 = "hello !!!"
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)