C++基础教程面向对象(学习笔记(100))

std :: string插入

插入

可以通过insert()函数将字符插入现有字符串。

string&string :: insert(size_type index,const string&str)
string&string :: insert(size_type index,const char * str)
//这两个函数都将str的字符插入到索引处的字符串中
//两个函数都返回*这样它们就可以被“链接”。
//如果索引无效,则两个函数都会抛出out_of_range
//如果结果超过最大字符数,则两个函数都会抛出length_error异常。
//在C风格的字符串版本中,str不能为NULL。
//示例代码:
string sString("aaaa");
cout << sString << endl;
 
sString.insert(2, string("bbbb"));
cout << sString << endl;
 
sString.insert(4, "cccc");
cout << sString << endl;
//输出:

AAAA
aabbbbaa
aabbccccbbaa

这是一个疯狂的insert()版本,它允许您将子字符串插入到任意索引的字符串中:

string&string :: insert(size_type index,const string&str,size_type startindex,size_type num)
//此函数将从startindex开始的num个字符str插入到index的字符串中。
//返回*这样就可以“链接”了。
//如果index或startindex超出范围,则抛出out_of_range
//如果结果超过最大字符数,则抛出length_error异常。
//示例代码:
string sString("aaaa");
 
const string sInsert("01234567");
sString.insert(2, sInsert, 3, 4); // insert substring of sInsert from index [3,7) into sString at index 2
cout << sString << endl;
//输出:

aa3456aa

有一种insert()可以插入C风格字符串的第一部分:

string&string :: insert(size_type index,const char * str,size_type len)
//将str的len个字符插入到索引处的字符串中
//返回*这样就可以“链接”了。
//如果索引无效,则抛出out_of_range异常
//如果结果超过最大字符数,则抛出length_error异常。
//忽略特殊字符(例如“)
//示例代码:
string sString("aaaa");
 
sString.insert(2, "bcdef", 3);
cout << sString << endl;
//输出:

aabcdaa

还有一种insert()可以多次插入相同的字符:

string&string :: insert(size_type index,size_type num,char c)
//将char c的num个实例插入到索引处的字符串中
//返回*这样就可以“链接”了。
//如果索引无效,则抛出out_of_range异常
//如果结果超过最大字符数,则抛出length_error异常。
//示例代码:
string sString("aaaa");
 
sString.insert(2, 4, 'c');
cout << sString << endl;
//输出:

aaccccaa

最后,insert()函数还有三个使用迭代器的不同版本:

void insert(iterator it,size_type num,char c)
iterator string :: insert(iterator it,char c)
void string :: insert(iterator it,InputIterator begin,InputIterator end)
//第一个函数在迭代器之前插入字符c的num个实例。
//第二个在迭代器之前插入单个字符c,并将迭代器返回到插入的字符的位置。
//第三个在迭代器之前插入[begin,end]之间的所有字符。
//如果结果超过最大字符数,则所有函数都会抛出length_error异常。

猜你喜欢

转载自blog.csdn.net/qq_41879485/article/details/84880001