0

我这里有一个程序,可以输出一个句子中的回文数。不区分大小写并忽略逗号和句点,例如回文恰好是句子中的最后一个单词。

#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。由于撇号,没有包括“女士”。

如果你给我看一个具体的代码,我会很高兴,这样我就很容易弄清楚要改变什么。但是,我仍然感谢您提供的任何帮助。:)

4

2 回答 2

3
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"由标点符号分隔,"'".

于 2012-01-25T10:14:17.063 回答
0

您的代码已经忽略了逗号和句点;将其扩展到包括撇号、冒号、分号和所有其他形式的标点符号。

于 2012-01-25T10:14:41.143 回答