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: