8.11.3 访问与修改字符串(3)
调用swap()成员函数可以交换封装在两个string对象之间的字符串。例如:
- string phrase("The more the merrier.");
- string query("Any");
- query.swap(phrase);
结果是query包含字符串"The more the merrier.",phrase包含字符串"Any"。当然,执行phrase.swap(query)也能得到同样的效果。
如果需要将一个字符串对象转换为以空字符结尾的字符串,可以用c_str()函数来完成。例如:
- string phrase("The higher the fewer");
- 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对象的引用。
举例如下:
- string proverb("A nod is as good as a wink to a blind horse");
- string sentence("It's bath time!");
- proverb.replace(38, 5, sentence, 5, 3);
这段代码采用表8-2中replace()函数的第4个版本,用"bat"替换字符串proverb中的"horse"。