设为首页 加入收藏

TOP

8.11.3 访问与修改字符串(2)
2013-10-07 16:09:43 来源: 作者: 【 】 浏览:95
Tags:8.11.3 访问 修改 字符串

8.11.3  访问与修改字符串(2)

执行这些语句的结果是query会包含字符串"Any more "。在最后一个语句中,对append()函数的第一个调用有3个实参:

第一个实参phrase是从中提取字符并附加到query后面的string对象。

第二个实参3是要提取的第一个字符的索引位置。

第三个实参5是要附加的字符总数。

因此这个调用会将子字符串"more"附加到query后面。对append()函数的第二个调用在query后面加上一个问号。

当想向一个字符串对象后面附加一个字符时,可以使用push_back()函数作为append()的替换函数。用法如下:

  1. query.push_back('*'); 

此代码向query字符串的末尾附加一个星号字符。

有时,仅仅向字符串末尾添加字符还不够。有时可能需要在字符串中间的某个位置插入一个或多个字符。insert()函数的各种版本可以完成这一任务:

  1. string saying("A horse");  
  2. string word("blind");  
  3. string sentence("He is as good as gold.");  
  4. string phrase("a wink too far");  
  5. saying.insert(1, " ");                     // Insert a space character  
  6. saying.insert(2, word);                    // Insert a string object  
  7. saying.insert(2, "nodding", 3);          // Insert 3 characters of a string literal  
  8. saying.insert(5, sentence, 2, 15);       // Insert part of a string at position 5  
  9. saying.insert(20, phrase, 0, 9);         // Insert part of a string at position 20  
  10. 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)作为实参。

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇8.11.3 访问与修改字符串(1) 下一篇8.11.3 访问与修改字符串(3)

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容:

·python数据分析岗的 (2025-12-25 10:02:21)
·python做数据分析需 (2025-12-25 10:02:19)
·成为一个优秀的pytho (2025-12-25 10:02:16)
·Java后端面试实习自 (2025-12-25 09:24:21)
·Java LTS版本有哪些 (2025-12-25 09:24:18)