溫馨提示×

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

c++
小億
339
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
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女