</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
回文
最新推荐文章于 2023-11-26 13:10:36 发布