Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any other way to Reverse String Without using array?

Tags:

c++

algorithm

int main()  
{  
    clrscr();  
    char c[80],d[80];  
    cout<<"Enter a string = ";  
    cin.get(a,80);  
    strcpy(c,a);  
    strrev(a);  
    if(strcmp(c,a)==0)  
         cout<<"String = "<<c<< "is palindrome.";  
    else  
         cout<<c<<" is not palindrome";  
    getch();  
    return 0;
}

so there is any other way to accomplish this task in easy way without using array or in other way?

like image 365
avirk Avatar asked Apr 21 '11 19:04

avirk


2 Answers

#include <string>
#include <algorithm>
#include <iostream>

int main()
{
    std::string s;
    getline(std::cin, s);

    if (std::equal(s.begin(), s.end(), s.rbegin()))
        std::cout << s << " is a palindrome\n";
    else
        std::cout << s << " is not a palindrome\n";
}

No arrays, no pointers.

like image 169
Robᵩ Avatar answered Sep 28 '22 00:09

Robᵩ


bool is_palindrome(const char* s)
{
    const char *p = s;
    const char *q = s + strlen(s) - 1;
    while (p < q) {
        if (*p != *q)
            return false;
        ++p;
        --q;
    } 
    return true;
}
like image 28
Igor Nazarenko Avatar answered Sep 28 '22 02:09

Igor Nazarenko