c++string insert、
时间: 2023-10-17 14:05:31 浏览: 31
C++ 中的 `string` 类型提供了 `insert` 函数用于在指定位置插入内容。该函数的语法如下:
```cpp
string& insert(size_t pos, const string& str);
string& insert(size_t pos, const char* s);
string& insert(size_t pos, const char* s, size_t n);
string& insert(size_t pos, size_t n, char c);
iterator insert(const_iterator p, size_t n, char c);
iterator insert(const_iterator p, char c);
template<class InputIterator>
void insert(iterator p, InputIterator first, InputIterator last);
```
其中:
- `pos` 表示要插入的位置,从 0 开始计数;
- `str` 表示要插入的字符串;
- `s` 表示要插入的 C 风格字符串;
- `n` 表示要插入的 C 风格字符串的长度;
- `c` 表示要插入的字符;
- `first` 和 `last` 表示要插入的字符范围;
- `p` 表示要插入的位置的迭代器。
下面是一些使用示例:
```cpp
#include <iostream>
#include <string>
using namespace std;
int main() {
string str = "hello world";
str.insert(5, "my"); // 在第 5 个字符后面插入 "my"
cout << str << endl; // 输出 "hello my world"
str.insert(0, "hi, "); // 在开头插入 "hi, "
cout << str << endl; // 输出 "hi, hello my world"
str.insert(14, 2, '!'); // 在第 14 个字符后面插入 2 个感叹号
cout << str << endl; // 输出 "hi, hello my world!!"
str.insert(str.begin() + 3, ' '); // 在第 3 个字符前面插入一个空格
cout << str << endl; // 输出 "hi, hello my world!!"
str.insert(str.begin() + 6, str.begin() + 10, str.end()); // 将第 6 个字符前面插入从第 10 个字符到结尾的字符
cout << str << endl; // 输出 "hi, my world!!hello my world!!"
return 0;
}
```