How do you print out a palindrome with certain characters removed using arrays?

狂风中的少年 提交于 2019-12-06 13:26:53

You forgot to add the terminating \0 to Reverse. Add *Palindrome = '\0' after the loop.

Just use separate iterators.

Instead of

for(i = 0; i != length/2; i++)

do

for(i = 0, j = length-1; i < j; i++, j--) 

then for your if statement, you can do something like

if(test) // if it is a palindrome so far
{
    while(!isalpha(Phrase[i]) && i < j) { i++; }
    while(!isalpha(Phrase[j]) && i < j) { j--; }
    if(Phrase[i] != Phrase[j]) //To check if the characters match
    {
        test = false;
    }

this will cause your program to ignore any character than isn't a letter. You can use isalphanum if you want it to recognize numbers as well.

#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] != ' ') && (ispunct(Phrase[k]) == false))
    {
        NewPhrase[l] = tolower(Phrase[k]);
        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])
            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;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!