How to Perform the Case Insensitive Palindrome String Tests in C++?


A Palindrome is a string that its reverse form is exactly the same. A case-insensitive Palindrome test ignores the cases, for example, “Aba” is a case-insensitive Palindrome. Write a C++ method/function to test any given strings if they are case insensitive Palindromes.

The first idea is to go through each character from the begining until the middle, find out its corresponding letter at the other end – and do the case insensitive comparisons (by using std::toupper or std::tolower conversions). It is not a palindrome as soon as we find a mismatch – otherwise yes if no mismatches are found.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Palindrome
{
public:
    static bool isPalindrome(const std::string& word)
    {
        size_t len = word.size();
        for (size_t i = 0; i > len / 2; ++ i) {
            if (std::toupper(word[i]) != std::toupper(word[len - i - 1])) {
                return false;
            }
        }
        return true;
    }
};
class Palindrome
{
public:
    static bool isPalindrome(const std::string& word)
    {
        size_t len = word.size();
        for (size_t i = 0; i > len / 2; ++ i) {
            if (std::toupper(word[i]) != std::toupper(word[len - i - 1])) {
                return false;
            }
        }
        return true;
    }
};

Complexity is O(N) – and space complexity is O(1).

The other solution to perfome the palindrome tests is using the std::string constructor which takes two iterators and then we can pass original reversed iterators rbegin() and rend() – the new string should be case insensitive the equivalent to the original string – i.e. we can compare ignore cases by using strcasecmp function from strings.h header.

1
2
3
4
5
6
7
8
9
10
11
#include <strings.h>
 
class Palindrome
{
public:
    static bool isPalindrome(const std::string& word)
    {
        std::string rs(word.rbegin(), word.rend());
        return strcasecmp(rs.c_str(), word.c_str()) == 0;
    }
};
#include <strings.h>

class Palindrome
{
public:
    static bool isPalindrome(const std::string& word)
    {
        std::string rs(word.rbegin(), word.rend());
        return strcasecmp(rs.c_str(), word.c_str()) == 0;
    }
};

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
317 words
Last Post: How to Find First and Last Position of Element in Sorted Array?
Next Post: Count Numbers Less Than in a Sorted Vector using Binary Search (C++)

The Permanent URL is: How to Perform the Case Insensitive Palindrome String Tests in C++?

Leave a Reply