ここに、1文の回文数を出力するプログラムがあります。大文字と小文字を区別せず、たとえば回文が文の最後の単語である場合は、コンマとピリオドを無視します。
#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」という単語がある場合を除いて、プログラムは正しく実行されます。たとえば、「こんにちは、奥様!私は綾です。」入力すると、プログラムは1を出力します。これは、1つの回文であるAyaを意味します。「ma'am」はアポストロフィのため含まれていません。
具体的なコードを教えていただければ幸いですので、何を変更すればよいかわかりやすくなります。それでも、どんな種類の助けにも感謝します。:)