Apr 23, 2014 at 6:48pm Apr 23, 2014 at 6:48pm UTC
I am trying to check a string to be a palindrome. I have tried using for loop but I am looking for most efficient way.
Thanks for the help.
Apr 23, 2014 at 8:03pm Apr 23, 2014 at 8:03pm UTC
booradley,
I don't understand your honor system comment.
This is what I have:
#include <iostream>
#include <string>
using namespace std;
//Prototypes
bool IsPalindrome(string words);
void StringCap(string &word);
//Main Function
int main()
{
string word;
bool palin;
cout << "Enter a string: ";
getline(cin,word);
cout << endl;
StringCap(word);
palin = IsPalindrome(word);
cout << word;
if(palin)
{
cout << word << " is a palindrome.";
}
else
{
cout << word << " is not a palindrome.";
}
return 0;
}
bool IsPalindrome(string words)
{
string reverse;
int x=0;
int count=0;
int value=0;
bool palindrome;
palindrome = true;
for(int i=0; i < count/2; i++)
{
value = words[i];
reverse[i]=words[count-1-i];
reverse[count-1-i] = value;
}
for(int b=0; b < count; b++)
{
if (words[b] == reverse[b])
{
x=1;
}
else
{
x=2;
}
}
if (x==1)
{
palindrome = true;
}
else
{
palindrome = false;
}
return palindrome;
}
void StringCap(string &word)
{
int i;
int length;
length = word.length();
for( i=0; i < length; i++ )
{
word[i] = toupper(word[i]);
}
}
Apr 23, 2014 at 9:50pm Apr 23, 2014 at 9:50pm UTC
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#include <iostream>
#include <algorithm>
#include <string>
//does not handle mixed uppercase and lowercase letters.
bool isPalindrome(const std::string& string) {
std::string reverse = string;
std::reverse(reverse.begin(), reverse.end());
return string == reverse;
}
int main(int argc, char * argv[]) {
std::string string = "racecar" ;
std::cout << "\"" << string << "\" is" << (isPalindrome(string) ? "" : "n't" ) << " a palindrome." << std::endl;
std::cin.get();
return 0;
}
Last edited on Apr 23, 2014 at 9:52pm Apr 23, 2014 at 9:52pm UTC