回文

</pre><div style="font-family:Arial; font-size:14px; line-height:22px"><pre name="code" class="cpp"> /** palindrome.cpp
 * 回文是一个单词或词组不管从前还是从后开始读,结果都一样。例如"madam"
 * 编写一个程序接受来自命令行的一个字符串参数,使用上一个练习中
 * 编写的字符串逆转函数reverse_str,打印出这个字符串是否是回文
 * 如果位置对称的两个字母大小写不同,例如 "Civic"任然返回true
 * 使其能够忽略标点符号和空格例如 "Able was I, ere I saw Elba."
 * 也报告true
 */
#include <iostream>
#include <cstdlib>
#include <cctype>  // for tolower
#include <string>
#include "utils.h" // for reverse_str
using namespace std;


//翻转字符串
string reverse_str(const string& s)
{
string str = s;
typedef string::size_type size;
size i = str.size();
for (size j = 0, k = i - 1; j <= k; j++,k--)
swap(str[j], str[k]);
return str;
}
//将字符串中的大写字母转换为小写字母
string lowerCase(const string& s)
{
string lower(s);
for (size_t i = 0; i < s.length(); i++)
lower[i] = tolower(s[i]);
return lower;
}

//删除字符串中的空格和标点符号
string remove_space_punct(const string& s)
{
size_t i = 0;
size_t j = 0;
string str(s);
for (; i < str.length(); i++)
{
if (!isspace(str[i]) && !ispunct(str[i]))
str[j++] = str[i];
}
//删除j到字符串末尾的剩余字符
str.erase(j, string::npos);
return str;
}
//如果字符串str是回文返回true,否则返回false
//if string str is palindrome return true, otherwise return false
bool isPalindrome(const string& str)
{
cout << "Original string s is:" << endl;
cout << "\"" << str  << "\"" << endl;

//将字符串中的大写字母转换成小写字母后再判断是否是回文
string s = lowerCase(str);
cout << "Cast uppercase to lowercase sting is:" << endl;
cout << "\"" << s << "\"" << endl;
// 删除字符串中的空格和标点
// erase spaces and punctuations in the string
string s1 = remove_space_punct(s);
cout << "Remove space and punctuation string is:" << endl;
cout << s1 << endl;
string reverse = reverse_str(s1);
if (s1 == reverse)
return true;
else
return false;
}

int main (int argc, char **argv)
{
if (argc != 2)
{
cout << "Usage: program  parameter" << endl;
exit(1);
}
cout << endl;
if (isPalindrome(string(argv[1])))
cout << "\"" << string(argv[1]) << "\"" << " is palindrome" << endl;
else
cout << "\"" << string(argv[1])<< "\"" <<" is not palindrome" << endl;
cout << endl;
return 0;
}


$g++ -g -Wall -opalindromeIgr palindromeIgr.cpp
$ ./palindromeIgr "Able was I, ere I saw Elba."

Original string s is:
"Able was I, ere I saw Elba."
Cast uppercase tolowercase string is:
"able was i, ere i saw elba."
Remove space and punctuation string is:
ablewasiereisawelba
"Able was I, ere I saw Elba." is palindrome


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值