A question I've been asked on interactive phone screens is to code a test to determine whether a string is
a palindrome or not. I am providing two examples here: one in C and one in C++. They both work and they both compile
without errors or warnings. I believe my C example is good, with the possible exception of variable names
(some of you may not like the register char* declarations, but they are valid in C).
My goal was an \$O(n)\$ solution with out reversing the string.
My question is about the C++ version, and I miss using iterators. Is there a way to make this more C++ like?
I can think in C; I can't necessarily think in C++.
Palindrome checker in C
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
bool palindromeChecker(char *possiblePalindrome)
{
bool isPalindrome = true;
size_t length = strlen(possiblePalindrome);
if (length < 3)
{
isPalindrome = false;
}
else
{
register char *leftSide = possiblePalindrome;
register char *rightSide = &possiblePalindrome[length-1];
while ((leftSide < rightSide) && isPalindrome)
{
if (*leftSide != *rightSide)
{
isPalindrome = false;
}
leftSide++;
--rightSide;
}
}
return isPalindrome;
}
int main(int argc, const char * argv[]) {
char testString[BUFSIZ];
bool iSPalendrome;
printf("Enter a test string to be checked for if it is a palindrome\n");
scanf("%s", testString);
iSPalendrome = palindromeChecker(testString);
printf("The test string %s is %s a palindrome\n", testString, (iSPalendrome? "" : "Not"));
}
Palindrome checker in C++
#include <iostream>
#include <string>
bool IsPalindrome(std::string PossiblePalindrome)
{
bool Palidrime = true;
if (PossiblePalindrome.size() < 3)
{
Palidrime = false;
}
else
{
std::string::iterator leftSide = PossiblePalindrome.begin();
std::string::iterator rightSide = PossiblePalindrome.end();
rightSide--; // end is past the end of the possible palindrome so decrement to point to a character.
while ((leftSide < rightSide) && Palidrime)
{
if (*leftSide != *rightSide)
{
Palidrime = false;
}
leftSide++;
rightSide--;
}
}
return Palidrime;
}
int main(int argc, const char * argv[]) {
// insert code here...
std::string PossiblePalindrome;
std::cout << "Enter a string to test to see if it is a palindrome.\n";
std::cin >> PossiblePalindrome;
std::cout << "The string " << PossiblePalindrome;
if (IsPalindrome(PossiblePalindrome))
{
std::cout << " is";
}
else
{
std::cout << " is not";
}
std::cout << " a palindrome" << std::endl;
}
registermight be valid C but that’s pretty irrelevant on a Code Review site. Is it good C? No: it’s pretty much obsolete. In fact, if the compiler honours it at all it’s more likely than not to screw with the compiler’s own, much superior optimisation logic. Don’t useregister. Definitely not here. \$\endgroup\$Palidrime. Is that a typo or am I just unaware of the word? \$\endgroup\$Palendrome. I think typos... \$\endgroup\$