簡體   English   中英

C ++中的回文掃描儀

[英]Palindrome scanner in 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;

您可以使用標准庫提供的算法來反轉數組。 看起來像這樣:

#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;
}

您甚至不需要費心創建反向字符串。 只需使用反向迭代器和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() 比較另一半只是反向進行相同的比較。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM