字符串常用函数之插入函数insert()的基本用法(C++少儿编程)
作者:野牛程序员:2023-06-20 10:21:10C++程序设计阅读 3253
在C++中,insert()函数用于在字符串中插入新的字符或字符串。它的基本语法如下:
string insert (size_t pos, const string& str);
其中,pos表示插入的位置,str表示要插入的字符串。函数将返回一个新的字符串,该字符串是在原始字符串的指定位置插入了新字符串后的结果。
下面是一个简单的示例程序,演示了insert()函数的基本用法:
#include <iostream>
#include <string>
using namespace std;
int main() {
string str = "Hello, world!";
cout << "原始字符串:" << str << endl;
// 在第7个位置插入字符串 "beautiful"
string newStr = str.insert(7, "beautiful");
cout << "插入后的字符串:" << newStr << endl;
return 0;
}输出结果:
原始字符串:Hello, world! 插入后的字符串:Hello, beautiful world!
在上面的示例中,我们首先创建了一个名为str的字符串,然后使用insert()函数在第7个位置插入了字符串"beautiful"。最后,将新的字符串存储在newStr变量中并打印输出。
需要注意的是,insert()函数会修改原始字符串,同时返回插入后的新字符串。如果你希望保留原始字符串,可以将返回值存储在另一个变量中。
野牛程序员教少儿编程与信息学奥赛-微信|电话:15892516892

