Palindrome

The following program determines if a given string is a palindrome.
Another way to do this is first to copy the string to another char[] and remove the non- alphabet characters from the string. Then copy it to the third char array and  reverse the order of the string . Finally compare the two strings.



#include
using namespace std;

#include

bool palindrome(char *p)
{
    char temp1, temp2;
    int i = 0; 
    int j = strlen(p)-1;
    while(i < j)
    {
        while ( (p[i] < 'a' && p[i] > 'Z') || p[i] < 'A' || p[i] > 'z') i++;
        if ( p[i] <= 'Z' && p[i] >= 'A') temp1 = ( p[i] + 32);
        else temp1 = p[i];

        while( (p[j] < 'a' && p[j] > 'Z') || p[j] < 'A' || p[j] > 'z') j--;
        if ( p[j] <= 'Z' && p[j] >= 'A') temp2 = ( p[j] + 32);
        else temp2 = p[j];

        if (temp1 != temp2) return false;

        i++; 
      j--;
    }
    return true;
}

int main()
{
    char a[100] = "A man a plan a canal panama";

    cout << boolalpha << palindrome(a) << endl;

    char b[100] ="Satanoscillatemymetallicsonatas";

    cout << boolalpha << palindrome(b) << endl;  

    char c[100] ="Sata,noscill atemy, metallic.sonatas";

    cout << boolalpha << palindrome(c) << endl;

    return 0;
}

No comments: