Check if palindrome

Hello guys,

I wrote a program that checks if text is palindrome.

I personally think it could be shorter than this (lines of code). How can I make this program better?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;

vector <char> reverseText(string someText)
{
	//covert string to vector of chars
	vector<char> textVec(someText.begin(), someText.end());
	//reverse the string using <algorithm>
	reverse(textVec.begin(), textVec.end());
	return textVec;
}

bool checkPalindrome(string someText)
{
	//convert the original string to a vector so we can compare between them.
	vector<char> OriginalText(someText.begin(), someText.end());
	vector <char> textReversed = reverseText(someText);
	if (OriginalText == textReversed)
	{
		return true;
	}
}

int main()
{
	string someText; 
	vector <char> textReversed;
	cout << "ENTER TEXT: ";
	cin >> someText;
	bool result = checkPalindrome(someText);
	cout << result << endl;
	system("PAUSE");
	return 0;
}
closed account (48bpfSEw)
Just compare the string with itself reversed:

1
2
3
4
5
6
7
8
string input;

cout << "Please enter a string: ";
cin >> input;

if (input == string(input.rbegin(), input.rend())) {
    cout << input << " is a palindrome";
}


found on http://stackoverflow.com/questions/8362572/check-if-a-string-is-palindrome

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <iostream>
#include <cctype>
#include <algorithm>
#include <iomanip>

bool is_palindrome( const std::string& str )
{
    // we want to ignore punctuation, white-space and capitalization
    std::string s ;
    for( char c : str ) if( std::isalnum(c) ) s += std::tolower(c) ;

    // we need to check only if the first half of the string is the reverse of the second half
    // std::equal - http://en.cppreference.com/w/cpp/algorithm/equal
    //              note: there is a palindrome example at the end of the page
    // rbegin() yields an iterator that iterates backward from the last character
    return !s.empty() && std::equal( s.begin(), s.begin()+s.size()/2, s.rbegin() ) ;
}

int main()
{
    const std::string phrases[] =
    {
        "Palindromes often consist of a phrase or sentence",
        "Punctuation, capitalization, and spacing are usually ignored",
        "A man, a plan, a canal - Panama!",
        "Do geese see God?"
    };

    for( const std::string& str : phrases )
         std::cout << std::quoted(str) << " - palinfrome? " << std::boolalpha << is_palindrome(str) << '\n' ;
}

http://coliru.stacked-crooked.com/a/1ad7192b3e9f1a78
Topic archived. No new replies allowed.