mardi 28 juillet 2020

C++ Comparing strings to determine palindrome

I am trying to determine if a string is a palindrome by reversing the string and then comparing the letters of both strings. The code is provided underneath. So far whatever I put I always get "is a palindrome " as an output. I am aware of the short cut method for doing this easily and efficiently but trying to understand the long way as well. I am using C++ 11

#include <iostream>
#include <string>

using namespace std;
string reversed = " ";

void reverse_sentence(string s)
{
    
    for (int i = 0; i <= s.length(); i++)
    {
        reversed = s[i] + reversed;
        
    }
    cout << reversed;
    
}

void is_pal(string reversed, string s)
{
    int flag = 0;
    
    // if(s == string(s.rbegin(), s.rend())){
    //   cout << "is a palindrome"<<endl;
    
    // }else{
    //   cout <<"failed"<<endl;
    
    // }
    
    for (int i = 0; i <= s.length(); i++)
    {
        for (int j = 0; j <= reversed.length(); j++)
        {
            if (s[i] != reversed[j - 1])
            {
                flag = 1;
            }
            
        }
    }
    if (flag == 1)
    {
        cout << "is palindrome" << endl;
    }
    else
    {
        cout << "not palindrome" << endl;
    }
}

int main()
{
    string s = "hello";
    reverse_sentence(s);
    is_pal(s, reversed);
    
    return 0;
    
}

Aucun commentaire:

Enregistrer un commentaire