3.3 使用string對(duì)象
無(wú)論是編寫(xiě)完整的字謎游戲還是簡(jiǎn)單地存儲(chǔ)玩家名字,第1章簡(jiǎn)單介紹過(guò)的string對(duì)象都非常適合于處理這樣的字符序列。string實(shí)際上是對(duì)象,它提供的成員函數(shù)允許用string對(duì)象完成一系列任務(wù),從簡(jiǎn)單地獲取對(duì)象長(zhǎng)度到復(fù)雜的字符替換等等。另外,string的定義方式使它可以直觀地與已知的一些運(yùn)算符一起使用。
3.3.1 String Tester程序簡(jiǎn)介
String Tester程序使用了一個(gè)等于"Game Over!!!"的字符串,并報(bào)告它的長(zhǎng)度、每個(gè)字符的索引(位置序號(hào))以及是否存在特定的子字符串。另外,程序還將該string對(duì)象的部分內(nèi)容擦除。該程序的運(yùn)行結(jié)果如圖3-3所示。
圖3-3 通過(guò)常見(jiàn)的運(yùn)算符和string成員函數(shù)可以對(duì)string對(duì)象進(jìn)行組合、修改和擦除操作
從Course Technology網(wǎng)站(www.courseptr.com/downloads)或本書(shū)合作網(wǎng)站(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;
}