Read a sentence and counts the number of palindromes in it. - C++ STL

C++ examples for STL:string

Introduction

A palindrome is a word that reads the same backward and forward. For example, "tree" is not a palindrome, but "noon" is.

Demo Code

#include <iostream>
#include <sstream>
#include <string>

int totalPalindromes(const std::string&);
bool isPalindrome(std::string&);

int main(int argc, const char* argv[]) {
    std::cout << "Enter a sentence: ";
    std::string base;/* w w  w  .  ja v a  2 s  .  c om*/

    std::getline(std::cin, base);

    std::cout << "\nYour sentence contains " << totalPalindromes(base)
              << " Palindromes." << std::endl;

    return 0;
}
// count and return total palindromes in given sentence
int totalPalindromes(const std::string& base) {
    std::stringstream ss(base);
    std::string word;
    int total = 0;

    while (std::getline(ss, word, ' ')) {
        total += ((isPalindrome(word)) ? 1 : 0);
    }

    return total;
}
// test if word is palindrome
bool isPalindrome(std::string& word) {
    std::string test = "";

    if (word.length() != 1) {
        std::string::reverse_iterator rit = word.rbegin();

        while (rit != word.rend()) {
            test += *(rit++);
        }
    }

    return (word == test);
}

Result


Related Tutorials