简体   繁体   中英

Palindrome scanner in C++

I've got a little problem with my palindrome "Scanner" in C++.

    #include <iostream>
    #include <string.h>
    #include <string>


    using namespace std;

    void start() {
        string eingabe;

        string umkehrung;
    cout << "Bitte geben Sie das Wort ein, von welchem getestet werden soll, ob es ein Palindrom ist!" << endl;
    cin >> eingabe;
    eingabe = ' ' + eingabe;
    for (int i = eingabe.length(); i >= 0; i--) {
        umkehrung = umkehrung + eingabe[i];

    }
    if (umkehrung == eingabe) {
        cout << "Das Wort '" + eingabe + "' ist ein Palindrom!" << endl;

    }
    else {
        cout << "Das Wort '" + eingabe + "' ist kein Palindrom!" << endl;
        cout << eingabe << endl;
        cout << umkehrung << endl;
    }


}

int main() {
    start();
    return 0;
}

It reverses the string input(Eingabe--->Umkehrung) and then checks if they are the same. But somehow it does always say they are not the same, even if they look the same (I output them here:

cout << eingabe << endl;
cout << umkehrung << endl;

You can use the algorithm provided by standard library to reverse the array. This would look like this:

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

using namespace std;

void start() {
    string eingabe;
    string umkehrung;

    cout << "Bitte geben Sie das Wort ein, von welchem getestet werden soll, ob es ein Palindrom ist!" << endl;
    cin >> eingabe;

    umkehrung = eingabe;
    std::reverse(umkehrung.begin(), umkehrung.end());

    if (umkehrung == eingabe) {
        cout << "Das Wort '" + eingabe + "' ist ein Palindrom!" << endl;

    }
    else {
        cout << "Das Wort '" + eingabe + "' ist kein Palindrom!" << endl;
        cout << eingabe << endl;
        cout << umkehrung << endl;
    }
}

int main() {
    start();
    return 0;
}

You don't even need to bother creating the reverse string; just use the reverse iterator and std::equal :

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

void check (const std::string& s) {
    auto s_is_a_palindrome = std::equal(s.begin(), s.end(), s.rbegin());
    std::cout << '"' << s << "\" is " << (s_is_a_palindrome ? "" : "not ")
              << "a palindrome\n";
}

int main() {
    check("hello olleh");
    check("hello, world");
}

And this program will indeed produce :

"hello olleh" is a palindrome
"hello, world" is not a palindrome

Note: You can stop comparing at half-length, ie s.begin() + s.length() / 2 should also be fine instead of s.end() . Comparing the other half is just doing the same comparisons in reverse.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM