/* * Copyright (c) 2002 by Cliff Green. All rights reserved. Individual files * may be covered by other copyrights (as noted in the file itself). * * Redistribution and use in source and binary forms are permitted * provided that this entire copyright notice is duplicated in all such * copies. * * This software is provided "as is" and without any expressed or implied * warranties, including, without limitation, the implied warranties of * merchantibility and fitness for any particular purpose. */ //---------------------------------------------------------------------- // Source file: pal.cpp // Written by: Cliff Green, 2002 // Compiler: Metrowerks CodeWarrior Pro 6, g++ 3.0.4 // History: // Modified: Mar. 5, 2002 // By: Cliff Green // Comments: See header file. //---------------------------------------------------------------------- // This commentheader supports documentation tools such as Doc++ and // Doxygen: http://www.doxygen.org/ //---------------------------------------------------------------------- /// PalCtr class implementation, performs palindrome detection and counting. /** * Keeps track of how many palindromes have been detected * by calling the isPalindrome method. */ #include "pal.h" #include // standard C++ header for traditional ctype.h #include // standard C++ header for traditional string.h // Note that C library headers with C++ std header names do not work // consistently in VC++ 5 / 6 - the traditional versions of C library // headers might need to be used, such as // Utility function to count the number of alpha chars in a C string int strlen_alpha (char const* s) { int cnt(0); while (*s != '\0') { if (std::isalpha(*s)) { ++cnt; } ++s; } return cnt; } // Note pre-condition documentation in header file bool PalCtr::isPalindrome (char const* begPtr) { if (strlen_alpha(begPtr) < 1) { // sanitize the input return false; } // At this point nothing will blow up inside this function. Also // note the char const type safety, and the C++ style of variable // initialization. // Compute beginning and end pointers char const* endPtr (begPtr + std::strlen(begPtr) - 1); while (begPtr < endPtr) { if (!std::isalpha(*begPtr)) { ++begPtr; continue; } if (!std::isalpha(*endPtr)) { --endPtr; continue; } if (std::toupper(*begPtr) != std::toupper(*endPtr)) { return false; } ++begPtr; --endPtr; } ++ mCnt; return true; }