首页 > 解决方案 > C++ 中的回文扫描器

问题描述

我在 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;
}

它反转字符串输入(Eingabe--->Umkehrung),然后检查它们是否相同。但不知何故,它总是说它们不一样,即使它们看起来一样(我在这里输出它们:

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

标签: c++

解决方案


您甚至不需要费心创建反向字符串;只需使用反向迭代器和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");
}

这个程序确实会产生

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

注意:您可以停止比较半长,即s.begin() + s.length() / 2应该也可以代替s.end(). 比较另一半只是反向进行相同的比较。


推荐阅读