我这里有一个程序可以输出一个句子中的回文数。不区分大小写并忽略逗号和句点,例如当回文恰好是句子中的最后一个单词时。
#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;
}
除了出现“ma'am”这个词,程序运行正常。例如,当“您好,女士!我是 Aya”时。输入后,程序只输出1,表示一个回文:Aya。由于撇号,“女士”未包括在内。
如果你给我一个具体的代码,我会很高兴,这样我就可以很容易地找出要改变的地方。但是,我仍然感谢您提供的任何帮助。 :)
最佳答案
wordStart = findNextLetter(line, wordEnd); // find start of next word wordEnd = findNextPunct(line, wordStart); // find end of next word
将单词定义为一串字母字符。
if (isPalindrome(line, wordStart, wordEnd))
正在检查一个词是否是回文。 "ma'am"
不是单词,因为它不仅仅由字母字符组成。 "ma'am"
是两个字"ma"
和 "am"
用标点符号分隔,"'"
.
关于c++ - 当我输入单词 "ma' am"时,程序不会将其视为回文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9000893/