Code Snippets

  

C++ Source Code


Welcome to Dream.In.Code
Getting C++ Help is Easy!

Join 119,691 C++ Programmers for FREE! Ask your question and get quick answers from experts. There are 2,109 online right now! We've got more than 500 tutorials and 2,000 snippets. Join and find out why Dream.In.Code is the #1 programming help community on the internet! Registration is fast and FREE... Join Now!




Check if a string is a palindrome

There are two versions, one which is case sensitive, and another which isn't case sensitive.

Submitted By: gabehabe
Actions:
Rating:
Views: 1,060

Language: C++

Last Modified: July 3, 2008

Snippet


  1. /**
  2.   * CHECK A STRING TO FIND OUT IF IT IS A PALINDROME
  3.   * BY DANNY BATTISON
  4.   * gabehabe@hotmail.com
  5.   */
  6.  
  7. #include <cctype> // tolower()
  8. #include <string>
  9.  
  10. /* Check if a word is a palindrome (case sensitive!) */
  11. bool isPalindrome (std::string word)
  12. {
  13.     for (unsigned int i = 0; i < (word.length()/2); i++)
  14.         if (word[i] != word[(word.length()-1)-i])
  15.             return false;
  16.  
  17.     /* If this point has been reached, then the word is a palindrome */
  18.     return true;
  19. }
  20.  
  21. /* CASE INSENSITIVE */
  22. bool isPalindromeCI (std::string word)
  23. {
  24.     /* Convert our string, character by character */
  25.     for (unsigned int i = 0; i < word.length(); i++)
  26.         word[i] = tolower(word[i]);
  27.     /* Now our word is all lower case, we can pass it to our other function */
  28.     return isPalindrome (word);
  29. }
  30.  
  31. /** EXAMPLE USAGE **/
  32.  
  33. #include <iostream>
  34.  
  35. int main ()
  36. {
  37.     bool palin = isPalindromeCI ("Hannah");
  38.     /* palin is true, since we use our case insensitive version */
  39.    
  40.     bool palin2 = isPalindrome ("Hannah");
  41.     /* palin2 is false, since isPalindrome is case sensitive */
  42.  
  43.     std::cin.get (); /* Pause */
  44.     return EXIT_SUCCESS; /* Program was executed successfully */
  45. }
  46.  

Copy & Paste


Comments


There are currently no comments for this snippet. Be the first to comment!

Add comment


You must be registered and logged on to </dream.in.code> to leave comments.





Live C++ Help!

C++ Tutorials

Reference Sheets

C++ Snippets

Bye Bye Ads

Free DIC T-Shirt

T-Shirt Example

Related Sites

Monthly Drawing

Thumb Drive

Partners

Top Contributors

Top 10 Kudos This Month