How to check if a string is a palindrome in C#

A palindrome refers to a series of characters, like a word, phrase, or number, that reads the same backwards or forwards. This unique quality of staying unchanged upon reversing its order often leads to intriguing patterns, contributing to the fascination with palindromes in programming challenges, algorithmic investigations, and tasks involving the manipulation of strings.

Example

Words like "civic", "deified", and "noon" demonstrate symmetry, appearing identical when read in either direction. Similarly, numeric palindromes like "12321" and "45654" maintain their integrity even when their digits are reversed.

Example of palindrome
Example of palindrome

Approaches

When approaching the task of determining whether a string is a palindrome in C#, various methodologies exist. However, for this specific discussion, we will focus on two fundamental strategies: an iterative and a recursive approach. The iterative method involves using two pointers to traverse the string from both ends towards the center, checking character equality at each step until the pointers meet.

On the other hand, the recursive approach employs a function that evaluates characters at opposite ends of the string, progressively moving inward and recursively calling itself to validate the remaining substring. Both approaches are reliable and offer distinct insights into how strings can be examined for palindrome properties in C#.

Iterative approach

In this approach, we traverse the string using two pointers, starting from both ends and moving towards the center. It offers insights into the efficiency of a linear iteration process for checking palindrome properties. It showcases how programmers can efficiently compare characters in a string using basic loop constructs, optimizing both time and space complexity. Let's look at the example below:

using System;
class Program
{
static bool IsPalindromeIterative(string str)
{
int left = 0, right = str.Length - 1;
while (left < right)
{
if (str[left] != str[right])
return false;
left++;
right--;
}
return true;
}
static void Main()
{
string word = "civic";
bool isPalindrome = IsPalindromeIterative(word);
if (isPalindrome)
{
Console.WriteLine("The given string is a palindrome.");
}
else
{
Console.WriteLine("The given string is not a palindrome.");
}
}
}

Code explanation

  • Lines 1–2: The code begins with the Program class declaration, utilizing the System namespace.

  • Lines 4–18: Defines a static method named IsPalindromeIterative within the Program class. This method checks whether a given string is a palindrome by iteratively comparing characters from both ends toward the middle.

  • Lines 20–33: The Main method, serving as the program’s entry point, initializes a string variable named word and checks if it’s a palindrome using the IsPalindromeIterative method. Based on the result, it prints a corresponding message to the console.

Recursive approach

On the other hand, the recursive method utilizes a recursive function to evaluate characters at opposite ends of the string. This approach offers insights into the elegance and flexibility of recursion in solving string manipulation problems. It demonstrates how a problem can be broken down into smaller subproblems, facilitating a concise and intuitive solution. Let's look at the example below:

using System;
class Program
{
static bool IsPalindromeRecursive(string str, int left, int right)
{
if (left >= right)
{return true;}
if (str[left] != str[right])
{return false;}
return IsPalindromeRecursive(str, left + 1, right - 1);
}
static void Main()
{
string word = "deified";
if (IsPalindromeRecursive(word, 0, word.Length - 1))
{Console.WriteLine("The given string is a palindrome.");}
else
{Console.WriteLine("The given string is not a palindrome.");}
}
}

Code explanation

  • Lines 1–2: The code begins with the Program class declaration, utilizing the System namespace, a fundamental namespace in C# programming.

  • Lines 4–13: Defines a static method named IsPalindromeRecursive within the Program class. This method uses recursion to determine whether a given string is a palindrome by comparing characters from both ends toward the middle.

  • Lines 15–23: The Main method, serving as the program's entry point, initializes a string variable word and checks if it's a palindrome using the IsPalindromeRecursive method. Based on the result, it prints a corresponding message to the console.

Conclusion

Whether to use an iterative or recursive approach for detecting a palindrome also depends on different aspects, such as performance, readability, and the nature of the problem.

  • Iterative methods are preferable for scenarios where efficiency and performance are critical, offering straightforward implementation and optimal resource usage. They excel in handling large input sizes and resource-constrained environments.

  • Recursive methods, on the other hand, shine in scenarios where the problem naturally decomposes into smaller subproblems and where code elegance and maintainability are valued. Despite potentially higher overhead, recursive solutions offer concise and intuitive implementations, particularly for problems with recursive properties.

By understanding the strengths and weaknesses of each approach, developers can make informed decisions to tackle palindrome detection and other string manipulation challenges effectively.

Copyright ©2024 Educative, Inc. All rights reserved