B3726 [语言月赛202303] String Problem P
#include <iostream>
using namespace std;
# include <string.h>
#include <ctype.h>
#include <algorithm>
#include <vector>
int main(){
int n,q;
cin>>n>>q;
vector<string> str(n);
for(auto & x:str) cin>>x;
while(q--){
int op;
cin>>op;
if(op == 1){
int x,y,i;
cin>>x>>y>>i;
str[y-1].insert(i,str[x-1]);
} else{
int y;
cin>>y;
cout<<str[y-1]<<endl;
}
}
}
`insert` 函数是 C++ 中 `std::string` 类的一个成员函数,用于在字符串中插入子字符串或字符。它提供了几种不同的重载形式,可以插入字符串、字符或指定范围的字符。
### 常用的 `insert` 函数形式
1. **插入字符串**
```cpp
string& insert(size_t pos, const string& str);
```
- **`pos`**:插入位置的索引,从 0 开始。
- **`str`**:要插入的字符串。
- **返回值**:返回对修改后的原始字符串的引用。
**示例**:
```cpp
string s = "hello";
s.insert(2, "ABC");
cout << s << endl; // 输出: heABCello
```
- 这里在位置 `2` 插入字符串 `"ABC"`,结果变为 `"heABCello"`。
表示的是下标从0开始,pos的位置上插入字符串。
2. **插入字符串的一部分**
```cpp
string& insert(size_t pos, const string& str, size_t subpos, size_t sublen);
```
- **`pos`**:插入位置的索引。
- **`str`**:要插入的字符串。
- **`subpos`**:要插入的 `str` 的起始位置。
- **`sublen`**:要插入的 `str` 的长度。
- **返回值**:返回对修改后的原始字符串的引用。
**示例**:
```cpp
string s = "hello";
string toInsert = "ABCDEFG";
s.insert(1, toInsert, 2, 3); // 从 "ABCDEFG" 中取位置 2 开始的 3 个字符插入到 s 中位置 1
cout << s << endl; // 输出: hCDEello
```
3. **插入 C 风格字符串**
```cpp
string& insert(size_t pos, const char* s);
```
- **`pos`**:插入位置的索引。
- **`s`**:要插入的 C 风格字符串(以 `\0` 结尾的字符数组)。
**示例**:
```cpp
string s = "hello";
s.insert(3, "XYZ");
cout << s << endl; // 输出: helXYZlo
```
4. **插入 C 风格字符串的一部分**
```cpp
string& insert(size_t pos, const char* s, size_t n);
```
- **`pos`**:插入位置的索引。
- **`s`**:要插入的 C 风格字符串。
- **`n`**:要插入的字符数量。
**示例**:
```cpp
string s = "hello";
s.insert(2, "12345", 3); // 只插入前 3 个字符 "123"
cout << s << endl; // 输出: he123llo
```
5. **插入多个相同字符**
```cpp
string& insert(size_t pos, size_t n, char c);
```
- **`pos`**:插入位置的索引。
- **`n`**:插入的字符数量。
- **`c`**:要插入的字符。
**示例**:
```cpp
string s = "hello";
s.insert(1, 3, 'A');
cout << s << endl; // 输出: hAAAllo
```
### 说明
- **`pos` 索引**:插入位置 `pos` 是基于 0 索引的,即字符串的第一个字符索引为 0,第二个字符索引为 1,以此类推。
- **超出边界的情况**:如果 `pos` 超出了字符串的长度,插入操作会将内容添加到字符串的末尾。
- **原字符串修改**:`insert` 操作会修改原字符串,并返回对修改后的字符串的引用。
### 实际示例
```cpp
#include <iostream>
#include <string>
using namespace std;
int main() {
string s = "abcdef";
// 在索引 2 处插入 "XYZ"
s.insert(2, "XYZ");
cout << s << endl; // 输出: abXYZcdef
// 插入部分字符串
string toInsert = "12345";
s.insert(1, toInsert, 2, 2); // 从 "12345" 中位置 2 开始取 2 个字符插入到索引 1
cout << s << endl; // 输出: a34bXYZcdef
// 插入多个相同字符
s.insert(0, 3, '*');
cout << s << endl; // 输出: ***a34bXYZcdef
return 0;
}
```
希望这能帮助你理解 `insert` 函数的用法!