3.3 使用string对象
无论是编写完整的字谜游戏还是简单地存储玩家名字,第1章简单介绍过的string对象都非常适合于处理这样的字符序列。string实际上是对象,它提供的成员函数允许用string对象完成一系列任务,从简单地获取对象长度到复杂的字符替换等等。另外,string的定义方式使它可以直观地与已知的一些运算符一起使用。
3.3.1 String Tester程序简介
String Tester程序使用了一个等于"Game Over!!!"的字符串,并报告它的长度、每个字符的索引(位置序号)以及是否存在特定的子字符串。另外,程序还将该string对象的部分内容擦除。该程序的运行结果如图3-3所示。
图3-3 通过常见的运算符和string成员函数可以对string对象进行组合、修改和擦除操作
从Course Technology网站(www.courseptr.com/downloads)或本书合作网站(http://www. tupwk.com.cn/downpage)上可以下载到该程序的代码。程序位于Chapter 3文件夹中,文件名为string_tester.cpp。
// String Tester
// Demonstrates string objects
#include <iostream>
#include <string>
using namespace std;
int main()
{
string word1 = "Game";
string word2("Over");
string word3(3, '!');
string phrase = word1 + " " + word2 + word3;
cout << "The phrase is: " << phrase << "\n\n";
cout << "The phrase has " << phrase.size() << " characters in it.\n\n";
cout << "The character at position 0 is: " << phrase[0] << "\n\n";
cout << "Changing the character at position 0.\n";
phrase[0] = 'L';
cout << "The phrase is now: " << phrase << "\n\n";
for (unsigned int i = 0; i < phrase.size(); ++i)
{
cout << "Character at position " << i << " is: " << phrase[i] << endl;
}
cout << "\nThe sequence 'Over' begins at location ";
cout << phrase.find("Over") << endl;
if (phrase.find("eggplant") == string::npos)
{
cout << "'eggplant' is not in the phrase.\n\n";
}
phrase.erase(4, 5);
cout << "The phrase is now: " << phrase << endl;
phrase.erase(4);
cout << "The phrase is now: " << phrase << endl;
phrase.erase();
cout << "The phrase is now: " << phrase << endl;
if (phrase.empty())
{
cout << "\nThe phrase is no more.\n";
}
return 0;
}