Click here to Skip to main content
Licence CPOL
First Posted 28 Aug 2008
Views 30,981
Bookmarked 12 times

Palindromes in C#

By | 28 Aug 2008 | Article
Algorithim for calculating if a string is a palindrome.

Introduction

This code calculates if a string is a palindrome, and was inspired by the Channel9 video by Gary Daniels and Evan Goldring - Mock whiteboard problem.

Background

There are two main approaches to calculating palindromes: byte symmetry, or on the basis of words. Byte symmetry checks to see if a string is a mirror image of itself "helloolleh", whilst the other approach handles white spaces "Was it Eliot's toilet I saw?"

Using the code

I've not inluded the code as an attachment, rather as inline text that can be used directly.

static bool isPalindrome(string subject)
{
  const int STEP_FORWARD = 1;
  const int STEP_BACKWARD = -STEP_FORWARD;
  const int BEFORE_START = -1;
  const int CHAR_AT_A_TIME = 1;
  const int COMPARE_EQUALS = 0;

  // assume its not a palindrome
  bool result = false;

  // how to compare
  CompareInfo ci = CultureInfo.CurrentCulture.CompareInfo;
  CompareOptions co =
    CompareOptions.IgnoreCase |
    CompareOptions.IgnoreKanaType |
    CompareOptions.IgnoreNonSpace |
    CompareOptions.IgnoreSymbols |
    CompareOptions.IgnoreWidth; |

  // null strings are not palindromes
  if (subject != null)
  {
    int AFTER_END = subject.Length;

    // single letter words are palindromes
    result = (AFTER_END == 1 && IsPalindromeChar(subject[0]));

    // start the comparison points at valid characters
    int startOffset = GetNextValidCharacter(subject, BEFORE_START, 
                                         STEP_FORWARD, AFTER_END);
    int endOffset = GetNextValidCharacter(subject, AFTER_END, 
                                STEP_BACKWARD, BEFORE_START);

    while (startOffset < endOffset)
    {
      result = ci.Compare(subject, startOffset, CHAR_AT_A_TIME, 
               subject, endOffset, CHAR_AT_A_TIME, co) == COMPARE_EQUALS;
  
      if (!result)
        break;

      // move the comparison points towards each other
      startOffset = GetNextValidCharacter(subject, startOffset, 
                                      STEP_FORWARD, endOffset);
      endOffset = GetNextValidCharacter(subject, endOffset, 
                               STEP_BACKWARD, startOffset);
    }
  }

  return result;
}

static int GetNextValidCharacter(string subject, int offset, 
                                 int step, int bound)
{
  if (offset != bound)
    offset += step;

  while (offset != bound && !IsPalindromeChar(subject[offset]))
    offset += step;

  return offset;
}   

static bool IsPalindromeChar(char c)
{
  return char.IsLetter(c) || char.IsDigit(c);
}

Points of interest

Reading the Wikipedia entry on palindromes shows that there are more than just alphabetical palindromes, so it is worth checking with your users before assuming that this code is what they mean by a palindrome.

On my blog, I've also included the byte symmetry code approach.

History

  • Aug/2008 - First version.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Philip Fitzsimons

Architect

United Kingdom United Kingdom

Member

still alive, just.
Campaign to bring back Windows 3.11 Look-N-Feel!

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
GeneralSimplified for C# PinmemberZamirF9:32 3 Feb '11  
Questionon the basis of words? PinmemberPIEBALDconsult11:42 29 Aug '08  
AnswerRe: on the basis of words? PinmemberPhilip Fitzsimons0:29 30 Aug '08  
GeneralAnother approach PinmemberRavi Bhavnani9:26 28 Aug '08  
GeneralRe: Another approach PinmemberPIEBALDconsult9:46 28 Aug '08  
GeneralRe: Another approach PinmemberRavi Bhavnani9:48 28 Aug '08  
GeneralRe: Another approach PinmemberPIEBALDconsult10:26 28 Aug '08  
GeneralRe: Another approach PinmemberRavi Bhavnani10:30 28 Aug '08  
GeneralRe: Another approach PinmemberPIEBALDconsult10:46 28 Aug '08  
GeneralRe: Another approach PinmemberRavi Bhavnani10:49 28 Aug '08  
GeneralRe: Another approach PinmemberPhilip Fitzsimons23:48 28 Aug '08  
GeneralRe: Another approach PinmemberRavi Bhavnani3:45 29 Aug '08  
GeneralRe: Another approach PinmemberJared Mcguire9:21 29 Aug '08  
GeneralRe: Another approach PinmemberPIEBALDconsult11:19 29 Aug '08  
GeneralOh goody PinmemberPIEBALDconsult6:35 28 Aug '08  
GeneralRe: Oh goody PinmemberPhilip Fitzsimons23:43 28 Aug '08  
nice! Smile | :)
though your comparasion does assume an exact match... Frown | :(
 



"When the only tool you have is a hammer, a sore thumb you will have."

GeneralRe: Oh goody PinmemberPIEBALDconsult4:22 29 Aug '08  
GeneralRe: Oh goody PinmemberPhilip Fitzsimons5:12 29 Aug '08  
GeneralRe: Oh goody [modified] PinmemberPIEBALDconsult10:28 29 Aug '08  
GeneralRe: Oh goody PinmemberPhilip Fitzsimons0:27 30 Aug '08  
GeneralRe: Oh goody PinmemberPIEBALDconsult7:58 30 Aug '08  

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Mobile
Web03 | 2.5.120604.1 | Last Updated 28 Aug 2008
Article Copyright 2008 by Philip Fitzsimons
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid