我的程序提示用户输入一个短语以检查其回文,然后应该打印出不带大写字母或特殊字符(如“”,“?”等)的短语。我的问题是删除这些字符。我的程序已忽略他们问我该如何删除它们?我在声明应该去的地方发表了评论。示例输出应为:“ Madam I'm Adam”(夫人我是亚当)到“ madamimadam”

#include <iostream>
#include <string>
#include <cctype>
    using namespace std;

int main()
{
    //Variables and arrays
    int const index = 80;
    char Phrase[index];
    char NewPhrase[index];
    int i, j, k, l;
    bool test = true;

    //Prompt user for the phrase/word
    cout << "Please enter a sentence to be tested as a palindrome: ";
    cin.getline(Phrase, 80);

    //Make everything lowercase, delete spaces, and copy that to a new array 'NewPhrase'
    for(k = 0, l = 0; k <= strlen(Phrase); k++)
    {
        if(Phrase[k] != ' ')
        {
            NewPhrase[l] = tolower(Phrase[k]);
            l++;
        }
    }
    //cout << "The Phrase without punctuation/extra characters: " << newPhrase[l];

    int length = strlen(NewPhrase); //Get the length of the phrase

    for(i = 0, j = length-1; i < j; i++, j--)
    {
        if(test) //Test to see if the phrase is a palindrome
        {
            if(NewPhrase[i] == NewPhrase[j])
            {;}
            else
            {
                test = false;
            }
        }
        else
            break;
    }

    if(test)
    {
        cout << endl << "Phrase/Word is a Palindrome." << endl << endl;
        cout << "The Palindrome is: " << NewPhrase << endl << endl;
    }
    else
        cout << endl << "Phrase/Word is not a Palindrome." << endl << endl;

    system("Pause");
    return 0;
}

最佳答案

修改此行:

if(Phrase[k] != ' ')


成为:

if((phrase[k] != ' ') && (ispunct(phrase[k]) == false))


这意味着我们要同时检查空格和标点符号。



另外,考虑重写以下内容:

if(NewPhrase[i] == NewPhrase[j])
        {;}
        else
        {
            test = false;
        }


因此:

if(NewPhrase[i] != NewPhrase[j])
   test = false;

10-07 19:52
查看更多