C++字符串插入

C++字符串插入教程

C++ 中,insert 函数用于将一个 字符串 插入到另一个字符串的指定位置,并返回插入字符串后的字符串。

C++字符串插入insert详解

语法

1. basic_string& insert( size_type index, size_type count, CharT ch ); 2. basic_string& insert( size_type index, const CharT* s ); 3. basic_string& insert( size_type index, const CharT* s, size_type count ); 4. basic_string& insert( size_type index, const basic_string& str ); 5. basic_string& insert( size_type index, const basic_string& str, size_type index_str, size_type count ); 6. basic_string& insert( size_type index, const basic_string& str, size_type index_str, size_type count = npos); 7. iterator insert( iterator pos, CharT ch ); iterator insert( const_iterator pos, CharT ch ); 8. void insert( iterator pos, size_type count, CharT ch ); 9. iterator insert( const_iterator pos, size_type count, CharT ch ); 10. void insert( iterator pos, InputIt first, InputIt last ); iterator insert( const_iterator pos, InputIt first, InputIt last );

insert函数说明

序号 功能
1 在 index 位置插入 count 个字符 ch
2 index 位置插入一个常量字符串
3 index 位置插入常量字符串中的 count 个字符
4 index 位置插入常量 string
5 index 位置插入常量 str 的从 index_str 开始的 count 个字符
6 index 位置插入常量 str 从 index_str 开始的 count 个字符,count 可以表示的最大值为 npos。
7 在 pos 位置处插入字符 ch
8 迭代器指向的 pos 位置插入 count 个字符 ch
9 迭代器指向的 pos 位置插入 count 个字符 ch
10 迭代器指向的 pos 位置插入一段字符串

说明

insert 函数提供了十个不同的重载。

案例

插入字符

C++ insert 函数在字符串中插入字符

#include <iostream> #include <string> using namespace std; int main() { cout << "嗨客网(www.haicoder.net)\n" << endl; string str = "Hello HaiCoder"; string retStr = str.insert(0, 5, 'A'); cout << "retStr = " << retStr << endl; return 0; }

程序运行后,控制台输出如下:

32_C字符串插入insert.png

我们首先,定义了一个字符串 变量 str,接着,我们使用了字符串的 insert 函数,在 str 的索引 0 处插入了五个字符 A,并返回插入的字符。

插入字符串

C++ insert 函数在字符串中插入字符串

#include <iostream> #include <string> using namespace std; int main() { cout << "嗨客网(www.haicoder.net)\n" << endl; string str = "Hello HaiCoder"; string retStr = str.insert(14, " Hello World!"); cout << "str = " << str << endl; cout << "retStr = " << retStr << endl; return 0; }

程序运行后,控制台输出如下:

33_C字符串插入insert.png

我们使用了 insert 函数,实现了在字符串 str 的索引为 14 的位置插入了一个字符串,最后,我们看到,返回了插入后的字符串,同时,原来的字符串也被修改了。

迭代器插入字符

C++ insert 函数可以使用迭代器在字符串中插入字符

#include <iostream> #include <string> using namespace std; int main() { cout << "嗨客网(www.haicoder.net)\n" << endl; string str = "Hello HaiCoder"; string::iterator it = str.insert(str.begin(), 'A'); cout << "str = " << str << endl; cout << "retStr = " << *it << endl; return 0; }

程序运行后,控制台输出如下:

34_C字符串插入insert.png

我们使用了 insert 函数加上迭代器在字符串中插入了字符,并返回了新的迭代器。

C++反向查找字符串教程

在 C++ 中 rfind 函数,用于从后往前查找字符串,如果查找到,则返回子串最后一次出现的位置,否则,返回 npos。