c++ primer plus 第16章string 类和标准模板库,16.1.3 使用字符串

c++ primer plus 第16章string 类和标准模板库,16.1.3 使用字符串

c++ primer plus 第16章string 类和标准模板库,16.1.3 使用字符串


16.1.3 使用字符串

现在,您知道可以使用不同方式来创建 string 对象、显示 sting 对象的内容、将数据读取和附加到 string 对象中、给 string 对象赋值以及将两个 string 对象连结起来。除此之外,还能做些什么呢?可以比较字符串。String类对全部6个关系运算符都进行了重载。如果在机器排列序列中,一个对象位于另一个对象的前面,则前者被视为小于后者。如果机器排列序列为 ASCI码,则数字将小于大写字符,而大写字符小于小写字符。对于每个关系运算符,都以三种方式被重载,以便能够将 string 对象与另一个string 对象、C-风格字符串进行比较,并能够将C-风格字符串与 string 对象进行比较:

string snakel("cobra");
string snake2("coral");
char snake3[20]="anaconda";
if(snakel<snake 2)
//operator<(const string &,const string &)
...
if(snakel == snake3)
//operator==(const string &,const char *)
::
if(snake3 != snake2)
//operator!=(const char *,const string &)

可以确定字符串的长度。size()和length()成员函数都返回字符串中的字符数:if(snakel.length()== snake2.size())

cout <<"Both strings have the same length.\n'

为什么这两个函数完成相同的任务呢?length()成员来自较早版本的string类,而size()则是为提供STL兼容性而添加的。
可以以多种不同的方式在字符串中搜索给定的子字符串或字符。表16.2简要地描述了 find()方法的4个版本。如前所述,string:npos是字符串可存储的最大字符数,通常是无符号int或无符号 long 的最大取值。
在这里插入图片描述
在这里插入图片描述
string 库还提供了相关的方法:rfind()、find first of()、find last of()、find first not of()和find last not of),它们的重载函数特征标都与 find()方法相同。rfind()方法查找子字符串或字符最后一次出现的位置;find firstof()方法在字符串中查找参数中任何一个字符首次出现的位置。例如,下面的语句返回r在“cobra”中的位置(即索引3),因为这是“hark”中各个字母在“cobra”首次出现的位置:int where =snakel.find first of(“hark”);
find last of()方法的功能与此相同,只是它査找的是最后一次出现的位置。因此,下面的语句返回a在“cobra”中的位置:
int where =snakel.last first of(“hark”);
tind first not ot)方法在字符用中查找第一个不包含在参数中的字符,因此下面的语句返回c在“cobra”中的位置,因为“hark”中没有c:
int where =snakel.find first not of(“hark”);
在本章最后的练习中,您将了解findlast notof()。
还有很多其他的方法,这些方法足以创建一个非图形版本的 Hangman 拼字游戏。该游戏将一系列的单词存储在一个 string 对象数组中,然后随机选择一个单词,让人猜测单词的字母。如果猜错6次,玩家就输了。该程序使用 find()函数来检查玩家的猜测,使用+=运算符创建一个 string 对象来记录玩家的错误猜测。为记录玩家猜对的情况,程序创建了一个单词,其长度与被猜的单词相同,但包含的是连字符。玩家猜对字符时,将用该字符替换相应的连字符。程序清单16.3列出了该程序的代码。

程序清单16.3 hangman.cpp

// hangman.cpp -- some string methods
#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>
#include <cctype>
using std::string;
const int NUM = 26;
const string wordlist[NUM] = {"apiary", "beetle", "cereal",
    "danger", "ensign", "florid", "garage", "health", "insult",
    "jackal", "keeper", "loaner", "manage", "nonce", "onset",
    "plaid", "quilt", "remote", "stolid", "train", "useful",
    "valid", "whence", "xenon", "yearn", "zippy"};

int main()
{
    using std::cout;
    using std::cin;
    using std::tolower;
    using std::endl;
    
    std::srand(std::time(0));
    char play;
    cout << "Will you play a word game? <y/n> ";
    cin >> play;
    play = tolower(play);
    while (play == 'y')
    {
        string target = wordlist[std::rand() % NUM];
        int length = target.length();
        string attempt(length, '-');
        string badchars;
        int guesses = 6;
        cout << "Guess my secret word. It has " << length
            << " letters, and you guess\n"
            << "one letter at a time. You get " << guesses
            << " wrong guesses.\n";
        cout << "Your word: " << attempt << endl;
        while (guesses > 0 && attempt != target)
        {
            char letter;
            cout << "Guess a letter: ";
            cin >> letter;
            if (badchars.find(letter) != string::npos
                || attempt.find(letter) != string::npos)
            {
                cout << "You already guessed that. Try again.\n";
                    continue;
            }
            int loc = target.find(letter);
            if (loc == string::npos)
            {
                cout << "Oh, bad guess!\n";
                --guesses;
                badchars += letter; // add to string
            }
            else
            {
                cout << "Good guess!\n";
                attempt[loc]=letter;
                // check if letter appears again
                loc = target.find(letter, loc + 1);
                while (loc != string::npos)
                {
                    attempt[loc]=letter;
                    loc = target.find(letter, loc + 1);
                }
           }
            cout << "Your word: " << attempt << endl;
            if (attempt != target)
            {
                if (badchars.length() > 0)
                    cout << "Bad choices: " << badchars << endl;
                cout << guesses << " bad guesses left\n";
            }
        }
        if (guesses > 0)
            cout << "That's right!\n";
        else
            cout << "Sorry, the word is " << target << ".\n";

        cout << "Will you play another? <y/n> ";
        cin >> play;
        play = tolower(play);
    }

    cout << "Bye\n";

    return 0; 
}

程序说明
在程序清单16.3中,由于关系运算符被重载,因此可以像对待数值变量那样对待字符串:

while(guesses >0&& attempt !=target)

与对C-风格字符串使用strcmp()相比,这样简单些,该程序使用 find()来检査玩家以前是否猜过某个字符。如果是,则它要么位于 badchars 字符串(猜错)中,要么位于attempt字符串(猜对)中:

if(badchars.find(letter)!= string::nposattempt.find(letter)!=string::npos)

npos 变量是 string 类的静态成员,它的值是 string 对象能存储的最大字符数。由于索引从0开始,所以它比最大的索引值大1,因此可以使用它来表示没有查找到字符或字符串。
该程序利用了这样一个事实:+=运算符的某个重载版本使得能够将一个字符附加到字符串中:

badchars +=letter;//append a char to a string object

该程序的核心是从检查玩家选择的字符是否位于被猜测的单词中开始的:

int loc=target.find(letter);

如果1oc是一个有效的值,则可以将该字母放置在答案字符串的相应位置

attempt[loc]=letter;

然而,由于字母在被猜测的单词中可能出现多次,所以程序必须一直进行检查。该程序使用了find()的第二个可选参数,该参数可以指定从字符串什么位置开始搜索。因为字母是在位置loc 找到的,所以下一次搜索应从1oc+1 开始。while循环使搜索一直进行下去,直到找不到该字符为止。如果loc 位于字符串尾,则表明find()没有找到该字符。

//check if letter appears again
loc =target.find(letter,loc+1);
while(loc != string::npos)
{
     attempt[loc]=letter;
    loc =target.find(letter,loc +1);
}
  • 30
    点赞
  • 24
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值