Fork me on GitHub

Project Notes

#173

Examples of how to code a palidrome check in C++.

Notes

Naïve Reversal

The most basic way of checking: reverse the string and then compare to the original. The std::swap function can be used to swap (reverse) all the characters in a string:

string reverse(string s) {
   int n = s.size();
   for (int i = 0; i < n / 2; ++i) swap(s[i], s[n - i - 1]);
   return s;
}

Range Comparison

The std::equal function can be used to write a one-line palindrome check by comparing two iterators over the input string:

  • one iterator starts at the begin of the string
  • the other iterator starts at the rbegin (reverse-beginning) of the string
  • the comparison stops when the first iterator reaches the end of the string.

So the following call will iterate through all characters and return true if palindromic:

equal(given.begin(), given.end(), given.rbegin())

This approach has the advantage of not creating any copies of the given string. It does suffer from checking all characters in the string, when it only needs to check to the halfway point.

Running the Example

See example.cpp for details. A makefile compiles and runs:

$ make
c++ -std=c++17 -g -Wall -O3    example.cpp   -o example
./example
If you type in a word, I'll tell you if it is a palindrome.
abc33cba
Checking by explicitly reversing the string: Yes, abc33cba is a palindrome.
Checking with a range comparison: Yes, abc33cba is a palindrome.
$ make
./example
If you type in a word, I'll tell you if it is a palindrome.
abc
Checking by explicitly reversing the string: No, abc is not a palindrome.
Checking with a range comparison: No, abc is not a palindrome.

Credits and References

About LCK#173 C++

This page is a web-friendly rendering of my project notes shared in the LittleCodingKata GitHub repository.

Project Source on GitHub Return to the LittleCodingKata Catalog
About LittleCodingKata

LittleCodingKata is my collection of programming exercises, research and code toys broadly spanning things that relate to programming and software development (languages, frameworks and tools).

These range from the trivial to the complex and serious. Many are inspired by existing work and I'll note credits and references where applicable. The focus is quite scattered, as I variously work on things new and important in the moment, or go back to revisit things from the past.

This is primarily a personal collection for my own edification and learning, but anyone who stumbles by is welcome to borrow, steal or reference the work here. And if you spot errors or issues I'd really appreciate some feedback - create an issue, send me an email or even send a pull-request.

Follow the Blog follow projects and notes as they are published in your favourite feed reader