设为首页 加入收藏

TOP

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

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

调用swap()成员函数可以交换封装在两个string对象之间的字符串。例如:

  1. string phrase("The more the merrier.");  
  2. string query("Any");  
  3. query.swap(phrase); 

结果是query包含字符串"The more the merrier.",phrase包含字符串"Any"。当然,执行phrase.swap(query)也能得到同样的效果。

如果需要将一个字符串对象转换为以空字符结尾的字符串,可以用c_str()函数来完成。例如:

  1. string phrase("The higher the fewer");  
  2. const char *pstring = phrase.c_str(); 

c_str()函数返回一个指向以空字符结尾的字符串的指针,该字符串的内容与string对象相同。

调用data()成员函数也可以获得一个字符串对象(作为char类型的数组)的内容。注意,该数组仅包含字符串对象中的字符,不包括结尾的空字符。

调用字符串对象的replace()成员函数可以替换字符串对象的一部分。它也有几个版本,如表8-2所示。

表  8-2

函 数 原 型
   
string& replace(size_t index,
         size_t count,
const char* pstring)
用pstring中的前count个字符替换从index
位置开始的count个字符
string& replace(size_t index,
         size_t count,
const string& astring)
用astring中的前count个字符替换从index
位置开始的count个字符
string& replace(size_t index,
         size_t count1,
const char* pstring,
size_t count2)
用pstring中第一个到第count2个字符替换从
index位置开始的count1个字符。这个版本允
许替换子字符串比被替换的子字符串更长或更短
string& replace(size_t index1,
         size_t count1,
const string& astring,
size_t index2,
size_t count2)
用astring中从index2位置开始的count2个字
符替换从index1位置开始的count1个字符
string& replace(size_t index,
         size_t count1,
size_t count2,
char ch)
用count2个字符ch替换从index位置开始的count1个字符

表8-2的各个版本都会返回对调用该函数的string对象的引用。

举例如下:

  1. string proverb("A nod is as good as a wink to a blind horse");  
  2. string sentence("It's bath time!");  
  3. proverb.replace(38, 5, sentence, 5, 3);  

这段代码采用表8-2中replace()函数的第4个版本,用"bat"替换字符串proverb中的"horse"。
 

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

评论

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

·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)