温馨提示×

c++中string insert的用法是什么

c++
小亿
134
2024-04-22 17:56:44
栏目: 编程语言

在C++中,string类的insert()函数用于在指定位置插入字符串、字符或另一个string对象的内容。

其基本语法如下:

string insert(size_t pos, const string& str);
string insert(size_t pos, const string& str, size_t subpos, size_t sublen);
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);

其中,pos参数表示要插入的位置(索引),str参数表示要插入的string对象或字符串,subpos参数表示从str中开始插入的位置,sublen参数表示要插入的长度,s参数表示要插入的C风格字符串,n参数表示要插入的字符个数,c参数表示要插入的字符。

下面是一些示例:

std::string str = "hello";
str.insert(2, "123"); // 结果为 "he123llo"

std::string str1 = "world";
std::string str2 = "hello";
str1.insert(0, str2); // 结果为 "helloworld"

std::string str3 = "hi";
str3.insert(1, 3, 'x'); // 结果为 "hxxxi"

0