Source of test_if_palindrome.cpp


  1: /** @file test_if_palindrome.cpp
  2: Determines if a string is a palindrome.
  3: */

  5: #include <iostream>
  6: #include <string>
  7: using namespace std;

  9: #include "utilities.h"
 10: using Scobey::Pause;
 11: using Scobey::ReadString;
 12: using Scobey::userSaysYes;

 14: bool isPalindrome
 15: (
 16:     const string s,          //in
 17:     string::size_type first, //in
 18:     string::size_type last   //in
 19:  )
 20: /**<
 21: Determine whether a string is a palindrome.
 22: @return true if s is a palindrome between the indices first
 23: and last (inclusive), false otherwise.
 24: @param s The full string to be tested.
 25: @param first The lower index of the portion of the string
 26: to be tested on the current call.
 27: @param The upper index of the portion of the string to be
 28: tested on the current call.
 29: @pre s contains a non-empty string object and 
 30: 0 <= first, last <= s.length().
 31: @post No side effects.
 32: */
 33: {
 34:     if (first >= last)
 35:         return true;
 36:     else
 37:         return (s[first] == s[last]) && 
 38:                 isPalindrome(s, first+1, last-1);
 39: }

 41: int main()
 42: {
 43:     cout << "\nThis program tests a string and "
 44:         "reports whether it is a palindrome.\n";
 45:     Pause();

 47:     do
 48:     {
 49:         string s;
 50:         ReadString("Enter the string on the following line: \n", s);
 51:         if (isPalindrome(s, 0, s.length()-1))
 52:             cout << "Yes, that was a palindrome.\n";
 53:         else
 54:             cout << "No, that was not a palindrome.\n";
 55:     }
 56:     while (userSaysYes("\nDo it again?"));
 57: }