簡體   English   中英

逐字回文程序

[英]Word by word palindrome program

因此,T找到了數以百萬計的回文程序示例,這些程序可以檢查單個單詞的回文。

但是,需要一個單詞接一個單詞的幫助,例如句子,你可以籠子吞下你不能吞下籠子,你可以吞下籠子嗎?”這將是一個單詞一個詞的回文。我只需要快速啟動本書給出的示例代碼即可這是

// FILE: pal.cxx
// Program to test whether an input line is a palindrome. Spaces,
// punctuation, and the difference between upper- and lowercase are ignored.

#include <cassert>    // Provides assert
#include <cctype>     // Provides isalpha, toupper
#include <cstdlib>    // Provides EXIT_SUCCESS
#include <iostream>   // Provides cout, cin, peek
#include <queue>      // Provides the queue template class
#include <stack>      // Provides the stack template class
using namespace std;

int main( )
{
queue<char> q;
stack<char> s;
char letter;            
queue<char>::size_type mismatches = 0;  // Mismatches between queue and stack
cout << "Enter a line and I will see if it's a palindrome:" << endl;

while (cin.peek( ) != '\n')
{
    cin >> letter;
    if (isalpha(letter))
    {
        q.push(toupper(letter));
        s.push(toupper(letter));
    }
}

while ((!q.empty( )) && (!s.empty( )))
{
    if (q.front( ) != s.top( ))
        ++mismatches;
    q.pop( );
    s.pop( );
}

if (mismatches == 0)
    cout << "That is a palindrome." << endl;
else
    cout << "That is not a palindrome." << endl;    
return EXIT_SUCCESS;    

}

實際上,從您的基本代碼中很容易做到這一點。 您只需要向隊列和堆棧中添加單詞(字符串)而不是char。 我迅速修改了代碼:

#include <algorithm>
queue<std::string> q;
stack<std::string> s;
std::string word;
queue<std::string>::size_type mismatches = 0;  // Mismatches between queue and stack
cout << "Enter a line and I will see if it's a palindrome:" << endl;

while (cin.peek( ) != '\n')
{
    cin >> word;
    std::transform(word.begin(), word.end(), word.begin(), ::toupper);
    q.push(word);
    s.push(word);
}

通過使用cin讀取字符串,您將自動使用空格作為分隔符。 該行:

std::transform(word.begin(), word.end(),word.begin(), ::toupper);

將字符串中的所有字符都轉換為大寫。

暫無
暫無

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

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