0

so I am making a palindrome checker that ignores any white space or special characters. Below is part of my function. What it does is it takes a c string as an argument, then I create another c string in order to remove the whitespaces and special character from the orignal. When I output the second c string, it still will have the whitespaces or special characters. Could some explain why it is doing that? Thanks

bool isPalindrome(char *line)
{
   //variables
   bool palindrome = true;
   int length = strlen(line);
   int count = 0;


   //copy line to line2 with no spaces and no punctuation
   char *line2 = new char[length + 1];
   int count2 = 0;

   for(int i = 0; i < length; i++)
   {
      if(line[i] != ' ' && ispunct(line[i]) == false)
      {
         line2[count2] = line[i];
         count2 ++;
      }
   }
   for(int i = 0; i < count2; i++)
       cout << line[i];
   line2[length] = '\0';
Derek Welton
  • 95
  • 1
  • 6

2 Answers2

1

You are null-terminating your second string at the original length:

line2[length] = '\0';

should be

line2[count2] = '\0';

As far as your original assignment goes, it is not necessary to create a copy of the string to check if it is a palindrome: all you need is a function that finds the next non-empty, non-punctuation character in a specific direction:

int nextValidChar(const char *str, int &pos, const int step) {
    pos += step;
    while (pos >= 0 && str[pos] != '\0') {
        char c = str[i];
        if (c != ' ' && !ispunct(c)) {
            return c;
        }
        pos += step;
    }
    return -1;
}

With this function in hand, set up two indexes, at zero and at length-1, and call nextValidChar repeatedly to find valid characters at both ends.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
1

The reason it is still outputting with spaces and special chars is because this

for(int i = 0; i < count2; i++)
   cout << line[i];

should be

for(int i = 0; i < count2; i++)
   cout << line2[i];
smrutled
  • 11
  • 3