我这里有一个程序,可以输出一个句子中的回文数。不区分大小写并忽略逗号和句点,例如回文恰好是句子中的最后一个单词。
#include <iostream>
#include <string>
using namespace std;
char toUpper(char c) {
if (c >= 'a' && c <= 'z')
return c - 'a' + 'A';
else
return c;
}
char isLetter(char c) {
return (toUpper(c) >= 'A' && toUpper(c) <= 'Z');
}
int findNextLetter(string& s, int start) {
// find first letter at or after 'start'
for (int i = start; i < s.length(); ++i) {
if (isLetter(s[i])) return i;
}
return s.length();
}
int findNextPunct(string& s, int start) {
// find first non-letter character at or after 'start'
for (int i = start; i < s.length(); ++i) {
if (!isLetter(s[i])) return i;
}
return s.length();
}
bool isPalindrome (const string& s, int start, int stop) {
// look for palindrome in the range (start) to (stop - 1)
for (int i = 0; i < (stop-start)/2; ++i) {
if (toUpper(s[start + i]) != toUpper(s[stop - 1 - i])) {
return false;
}
}
return true;
}
int main() {
string line;
int counter=0;
cout << "Please input a sentence." << endl;
getline(cin, line);
int wordStart = findNextLetter(line, 0);
int wordEnd = findNextPunct(line, wordStart);
while (wordStart != line.length()) {
if (isPalindrome(line, wordStart, wordEnd))
++counter;
wordStart = findNextLetter(line, wordEnd); // find start of next word
wordEnd = findNextPunct(line, wordStart); // find end of next word
}
cout << "Number of Palindromes: " << counter << endl;
}
程序正常运行,除非有“女士”一词。例如,当“你好,女士!我是 Aya”时。输入,程序只输出1,表示一个回文:Aya。由于撇号,没有包括“女士”。
如果你给我看一个具体的代码,我会很高兴,这样我就很容易弄清楚要改变什么。但是,我仍然感谢您提供的任何帮助。:)