《C++ Primer Plus(第六版)》(36)(第十六章 string类和标准模板库 编程练习和答案)

16.10 编程练习

1.回文指的是顺着读和逆着读都一样的字符串。假如,“tot"和“otto”都是简短的回文。编写一个程序,让用户输入字符串,并将字符串引用传递给一个bool函数。如果字符串是回文,该函数将返回true,否则返回false。此时,不要担心诸如大小写、空格和标点符号这些复杂的问题。即这个简单的版本将拒绝“Otto”和“Madam,I'm Adam”。请查看附录F中字符串方法列表,以简化这项任务。

//
//  main.cpp
//  HelloWorld
//
//  Created by feiyin001 on 16/12/30.
//  Copyright (c) 2016年 FableGame. All rights reserved.
//
#include <iostream>
#include <string>
#include <cstring>
#include "Test.h"
using namespace std;
using namespace FableGame;

bool check(const string& str)
{
    string temp = str;
    reverse(temp.begin(), temp.end());
    return str == temp;
}


int main()
{
    cout << "Enter a Palindrome: ";
    string str;
    while (cin >> str) {
        if (check(str)) {
            cout << str << " is Palindrome" << endl;
        }
        else
        {
            cout << str << " is not Palindrome" << endl;
        }
        cout << "Enter a Palindrome: ";
    }
    return 0;
}

2.与编程练习1中给出的问题相同,但要考虑诸如大小写、空格和标点符号这样的复杂问题。即“Madam, I‘m Adam”将作为回文来测试。例如,测试函数可能会将字符串缩略为“madamimadam”,然后测试倒过来是否一样。不要忘了有用的cctype库,您可能从中找到几个有用的STL函数,尽管不一定非要使用它们。

//
//  main.cpp
//  HelloWorld
//
//  Created by feiyin001 on 16/12/30.
//  Copyright (c) 2016年 FableGame. All rights reserved.
//
#include <iostream>
#include <string>
#include <cstring>
#include <cctype>
#include "Test.h"
using namespace std;
using namespace FableGame;

bool check(const string& str)
{
    string temp0;
    for (int i = 0; i < str.length(); i++) {
        if (islower( str[i] )) {
            temp0.push_back(str[i]);
        }
        else if(isupper(str[i]))
        {
            temp0.push_back(tolower(str[i]));
        }
    }
    string temp = temp0;
    reverse(temp.begin(), temp.end());
    return temp0 == temp;
}


int main()
{
    cout << "Enter a Palindrome: ";
    string str;
    
    while ( cin && getline(cin, str)) {
        
        if (check(str)) {
            cout << str << " is Palindrome" << endl;
        }
        else
        {
            cout << str << " is not Palindrome" << endl;
        }
        cout << "Enter a Palindrome: 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值