I'm brand new to C++ and I have a little Java experience.
I am testing for palindromes and I want to compare an array to itself inversely. Is there a function that does this already or will I have to write something?
I currently have this, but the second for loop isn't returning the inverse array.
#include <iostream>
#include <string>
usingnamespace std;
int main()
{
string UserProvidedWord;
cout << "Word: ";
cin >> UserProvidedWord;
cout << UserProvidedWord << "\n";
int lengthOfProvidedWord = UserProvidedWord.length();
string ComparisonArray[100];
int differential = lengthOfProvidedWord;
for(int i = 0;i < UserProvidedWord.length();i++)
{
ComparisonArray[i] = UserProvidedWord[i];
for(int y = differential; y < 0; y--)
{
if(ComparisonArray[y] == ComparisonArray[i])
{
cout << UserProvidedWord << " is a palindrome";
}
else
{
cout << "This is not a palindrome";
}
}
}
}
The idea is that by outputting the array values from the highest to lowest (y--), it would print out the last letter until it reached the first letter in the array. The y for loop isn't working for some reason.
#include <iostream>
#include <cctype>
#include <algorithm>
bool is_palindrome( const std::string& str )
{
// we want to ignore punctuation, whitespace, capitalization and non-printable chars
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
// http://en.cppreference.com/w/cpp/string/basic_string/rbeginreturn !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 ) if( is_palindrome(str) )
std::cout << str << '\n' ;
}