Search code examples
c++palindrome

Function that verify's if the string is a palindrom


right now I'm working on a program which tells you if the string you entered is a palindrome or not, and I am stuck on the last step. There are three essential functions which remove all spaces in a sentence, drop them to lower case, and reverse them, then that's when my function verify's them then returns a boolean value. So right now in this function, Happy Birthday! will come out as yadhtribyppah. This is what I have in my function so far:

string updated1;
string updated2;

updated1 = makeLower(verify);

updated2 = removeNonLetters(updated1);

updated1 = reverse(updated2);


for (int i = 0; i < updated2.length(); i++)
{
    if (updated2[i] != updated1[i])
    {
        break;
        return false;
    }
    else if (updated2[i] == updated1[i])
    {
        return true;

    }



}

}


Solution

  • Assuming there are no errors in your other functions, change your for loop to:

    for (int i = 0; i < updated2.length(); i++)
    {
        // If we find even one inequality, we know its not a palindrome.
        if (updated2[i] != updated1[i])
            return false;
    }
    // if the for loop has been executed satisfactorily, we know that it is a palindrome.
    return true;