8.11.3 访问与修改字符串(2)
执行这些语句的结果是query会包含字符串"Any more "。在最后一个语句中,对append()函数的第一个调用有3个实参:
第一个实参phrase是从中提取字符并附加到query后面的string对象。
第二个实参3是要提取的第一个字符的索引位置。
第三个实参5是要附加的字符总数。
因此这个调用会将子字符串"more"附加到query后面。对append()函数的第二个调用在query后面加上一个问号。
当想向一个字符串对象后面附加一个字符时,可以使用push_back()函数作为append()的替换函数。用法如下:
- query.push_back('*');
此代码向query字符串的末尾附加一个星号字符。
有时,仅仅向字符串末尾添加字符还不够。有时可能需要在字符串中间的某个位置插入一个或多个字符。insert()函数的各种版本可以完成这一任务:
- string saying("A horse");
- string word("blind");
- string sentence("He is as good as gold.");
- string phrase("a wink too far");
- saying.insert(1, " "); // Insert a space character
- saying.insert(2, word); // Insert a string object
- saying.insert(2, "nodding", 3); // Insert 3 characters of a string literal
- saying.insert(5, sentence, 2, 15); // Insert part of a string at position 5
- saying.insert(20, phrase, 0, 9); // Insert part of a string at position 20
- saying.insert(29, " ").insert(30, "a poor do", 0, 2);
执行上面的语句后,saying将包含字符串"A nod is as good as a wink to a blind horse"。insert()的各版本的形参如表8-1所示。
表 8-1
|
函 数 原 型
|
说 明
|
|
string& insert(size_t index,
const char* pstring)
|
在index位置插入以空字符结尾的字符串pstring
|
|
string& insert(size_t index,
const string& astring)
|
在index位置插入string对象astring
|
|
string& insert(size_t index,
const char* pstring,
size_t count)
|
在index位置插入以空字符结尾的字符串
pstring中的前count个字符
|
|
string& insert(size_t index,
size_t count,
char ch)
|
在index位置插入字符ch的count个副本
|
|
string& insert(size_t index,
const string& astring,
size_t start,
size_t count)
|
在string对象astring中从start位置的字符开
始的count个字符;子字符串插入在index位置
|
insert()的这些版本都返回对调用该函数的string对象的一个引用。这样,就可以像上面代码片段中的最后一个语句那样将所有调用链接在一起。
表8-1并不是insert()函数的完整集合,但是可以用该表中的版本做任何事情。其他版本用第10章将介绍的迭代器(iterator)作为实参。