Click here to Skip to main content
6,291,124 members and growing! (15,730 online)
Email Password   helpLost your password?
General Programming » Algorithms & Recipes » General     Intermediate License: The Code Project Open License (CPOL)

Palindromes in C#

By Philip Fitzsimons

Algorithim for calculating if a string is a palindrome.
C# (C# 1.0, C# 2.0, C# 3.0), .NET, Dev
Posted:28 Aug 2008
Views:9,352
Bookmarked:9 times
Announcements
Loading...
 
Search    
Advanced Search
printPrint   Broken Article?Report       add Share
  Discuss Discuss   Recommend Article Email
3 votes for this article.
Popularity: 1.81 Rating: 3.80 out of 5

1
1 vote, 33.3%
2

3

4
2 votes, 66.7%
5

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


Member
still alive, just.
Campaign to bring back Windows 3.11 Look-N-Feel!
Occupation: Architect
Location: United Kingdom United Kingdom

Other popular Algorithms & Recipes articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 20 of 20 (Total in Forum: 20) (Refresh)FirstPrevNext
Generalon the basis of words? PinmemberPIEBALDconsult12:42 29 Aug '08  
GeneralRe: on the basis of words? PinmemberPhilip Fitzsimons1:29 30 Aug '08  
GeneralAnother approach PinmemberRavi Bhavnani10:26 28 Aug '08  
GeneralRe: Another approach PinmemberPIEBALDconsult10:46 28 Aug '08  
GeneralRe: Another approach PinmemberRavi Bhavnani10:48 28 Aug '08  
GeneralRe: Another approach PinmemberPIEBALDconsult11:26 28 Aug '08  
GeneralRe: Another approach PinmemberRavi Bhavnani11:30 28 Aug '08  
GeneralRe: Another approach PinmemberPIEBALDconsult11:46 28 Aug '08  
GeneralRe: Another approach PinmemberRavi Bhavnani11:49 28 Aug '08  
GeneralRe: Another approach PinmemberPhilip Fitzsimons0:48 29 Aug '08  
GeneralRe: Another approach PinmemberRavi Bhavnani4:45 29 Aug '08  
GeneralRe: Another approach PinmemberJared Mcguire10:21 29 Aug '08  
GeneralRe: Another approach PinmemberPIEBALDconsult12:19 29 Aug '08  
GeneralOh goody PinmemberPIEBALDconsult7:35 28 Aug '08  
GeneralRe: Oh goody PinmemberPhilip Fitzsimons0:43 29 Aug '08  
GeneralRe: Oh goody PinmemberPIEBALDconsult5:22 29 Aug '08  
GeneralRe: Oh goody PinmemberPhilip Fitzsimons6:12 29 Aug '08  
GeneralRe: Oh goody [modified] PinmemberPIEBALDconsult11:28 29 Aug '08  
GeneralRe: Oh goody PinmemberPhilip Fitzsimons1:27 30 Aug '08  
GeneralRe: Oh goody PinmemberPIEBALDconsult8:58 30 Aug '08  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 28 Aug 2008
Editor: Smitha Vijayan
Copyright 2008 by Philip Fitzsimons
Everything else Copyright © CodeProject, 1999-2009
Web13 | Advertise on the Code Project