一、基础用法
string insert函数是c++中的一个非常重要的字符串操作函数,它用于在字符串中插入字符、字符串或者其他类型的数据。insert函数的基本用法如下:
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);
上述四个函数分别用于在字符串的指定位置插入字符串str、字符指针s、指定字符数的字符指针s,以及指定数量的字符c。下面是一个简单的插入示例:
#include using namespace std; int main() { string str1 = "Hello World!"; str1.insert(6, "C++ "); cout << str1 << endl; // Hello C++ World! return 0; }
上面的代码中,使用insert函数在字符串的第六个位置插入了”C++ “。输出结果为”Hello C++ World!”。
二、高级用法
除了基本用法外,insert函数还可以实现一些高级的插入操作,下面将介绍几种常用的高级用法:
1. 插入子串
使用insert函数插入子串需要注意一些细节。首先,插入的子串需要用双引号括起来;其次,插入的位置是子串的起始位置;最后,插入的长度是子串的长度。下面的示例演示了如何在字符串中插入子串:
#include using namespace std; int main() { string str1 = "Hello World!"; string str2 = "C++ "; str1.insert(6, str2, 0, str2.size()); //插入str2的子串 cout << str1 << endl; // Hello C++ World! return 0; }
上面的代码中,使用insert函数在字符串的第六个位置插入了str2的子串。输出结果为”Hello C++ World!”。
2. 插入重复字符串
insert函数还可以用于插入重复的字符串,只需要指定插入的数量即可。下面的示例演示了如何在字符串中插入重复的字符串:
#include using namespace std; int main() { string str1 = "World!"; str1.insert(str1.begin(), 3, 'H'); cout << str1 << endl; //HHHWorld! return 0; }
上面的代码中,使用insert函数在字符串的起始位置插入了3个字符’H’。输出结果为”HHHWorld!”。
3. 插入其他类型的数据
insert函数还可以用于插入其他类型的数据,比如整型、浮点型等等。只需要先将其他类型的数据转换为字符串,然后再进行插入即可。下面的示例演示了如何在字符串中插入整型数据:
#include #include using namespace std; int main() { string str = "World!"; int num = 100; stringstream ss; ss << num; str.insert(0, ss.str()); cout << str << endl; // 100World! return 0; }
上面的代码中,首先将整型数据num通过stringstream流转换为字符串,然后使用insert函数在字符串的起始位置插入该字符串。输出结果为”100World!”。
4. 使用迭代器插入
除了使用位置参数插入,在使用insert函数时还可以使用迭代器来进行插入操作。
#include #include using namespace std; int main(){ string str = "World"; str.insert(str.begin() + 2, 'H'); cout << str << endl; //WoHrld return 0; }
上面的代码中,使用insert函数在字符串的第2个位置插入了字符’H’。输出结果为”WoHrld”。
三、总结
本文介绍了c++中字符串操作函数insert的多个用法。除了基本的函数用法外,还介绍了插入子串、插入重复字符串、插入其他类型的数据和使用迭代器插入等高级用法。使用insert函数可以非常方便地在字符串中进行插入操作。
原创文章,作者:KWCAU,如若转载,请注明出处:https://www.506064.com/n/333226.html