C++编程思想 第2卷 第3章 深入理解字符串 对字符串进行操作 追加、插入和连接字符串

有用C语言编程经验的人,都习惯用函数族对char型数组进行写入、
查找、修改和复制等操作

标准C语言的char型数组工具中存在其固有的第2个误区,那就是它们
都显示地依赖一种假设:字符数组包括一个空结束符

C++提供的string类对象,在使用的便利性和安全性上都有很大的提高

C++字符串有几个颇具价值而且最便于使用的特色,其中之一就是:无需
程序员干预,它们可根据需要自行扩充规模

当字符串增长时,字符串成员函数append()和insert()很明显地重新
分配了存储空间

//: C03:StrSize.cpp
// From "Thinking in C++, Volume 2", by Bruce Eckel & Chuck Allison.
// (c) 1995-2004 MindView, Inc. All Rights Reserved.
// See source code use permissions stated in the file 'License.txt',
// distributed with the code package available at www.MindView.net.
#include <string>
#include <iostream>
using namespace std;

int main() {
  string bigNews("I saw Elvis in a UFO. ");
  cout << bigNews << endl;
  // How much data have we actually got?
  cout << "Size = " << bigNews.size() << endl;
  // How much can we store without reallocating?
  cout << "Capacity = " << bigNews.capacity() << endl;
  // Insert this string in bigNews immediately
  // before bigNews[1]:
  bigNews.insert(1, " thought I");
  cout << bigNews << endl;
  cout << "Size = " << bigNews.size() << endl;
  cout << "Capacity = " << bigNews.capacity() << endl;
  // Make sure that there will be this much space
  bigNews.reserve(500);
  // Add this to the end of the string:
  bigNews.append("I've been working too hard.");
  cout << bigNews << endl;
  cout << "Size = " << bigNews.size() << endl;
  cout << "Capacity = " << bigNews.capacity() << endl;
  getchar();
} ///:~

输出
I saw Elvis in a UFO.
Size = 22
Capacity = 31
I thought I saw Elvis in a UFO.
Size = 32
Capacity = 47
I thought I saw Elvis in a UFO. I've been working too hard.
Size = 59
Capacity = 511

这个例子证实了,即使可以安全地避免分配及管理string对象所占用
的存储空间的工作,C++ string类也提供了几个工具以便监视和
管理它们的存储规模

size()函数返回当前在字符串存储的字符数,它跟length()成员函数
的作用是一样的

capacity()函数返回当前分配的存储空间的规模,也即在没有要求
更多存储空间时,字符串所能容纳的最大字符串

reserve()函数提供一种优化机制,按程序员的意图,预留一定数量
的存储空间,以便将来使用

string类的成员函数为数据分配存储空间的确切方式取决于C++类库
的实现

当系统进行存储空间再分配遇到偶数字 的边界时,会隐含增加一个字节

string类的设计者曾经做过不懈的努力让char型数组和C++字符串对象
可以混合使用,在特定的实现中,意味着预留出一个字节以便很容易
容纳空结束符

猜你喜欢

转载自blog.csdn.net/eyetired/article/details/81664623