C++: Check if the String is Palindrome

1. #include <iostream>
2. #include <algorithm>
3. #include <string>

4. bool is_palindrom(const std::string& str)
5. {
6.    std::string temp(str);
7.    std::transform(temp.begin(), temp.end(), temp.begin(), ::tolower);
8.    return temp == std::string(temp.rbegin(), temp.rend());
9. }

10. int main()
11. {
12.    std::string str{ "KArak" };
13.    std::cout << is_palindrom(str) << std::endl;
14.    return 0;
15. }

We are not writing using namespace std because it 

forces all includers of that header file to use that namespace, which might result in naming ambiguities that are hard to fix. This practice is called namespace pollution. Instead, always use the fully prefixed names in header files (std::string not string) and save the using declarations for the source files.

In line 7 transform algorithm is used. It applies a function to a range of elements and stores the outcome in new sequence. The function used is tolower which lowers all the capital alphabets.An example of Transform Algorithm 

In line 8 string stored in temp is checked with its reverse string. If they both matches output is 1 otherwise 0.

Detailed Discussion

You may also like:
How do I improve my logical thinking and problem solving skills?
C++:Recursive Merge Sort
C++: Pointers, Virtual Function
C++: Implementation of Quicksort
Cool Websites you don't know about...

Popular Posts

Top 10 Web Sites Every Programmer Should Visit Daily

How do I improve my logical thinking and problem solving skills?

C++: STL Iterators