首页 > 解决方案 > palindrome c program is not working for some reason

问题描述

this program checks weather the entered string is palindrome or not . it should be in a way like it should even tell the string is palindrome if there is space or any special character

like messi is a palindrome of iss em

and ronald!o is a palindrome of odlanor

this is the program and for some odd reason it is strucking and not working

#include <stdio.h>
#include <string.h>

int main() {

  char palstr[100], ans[100];

  printf("enter the string for checking weather the string is a palindrome or not");

  scanf("%[^/n]", &palstr);

  int ispalin = 1, i = 0, n = 0;

  int num = strlen(palstr);

  printf("the total length of the string is %d", num);
  while (i <= num) {
    if (palstr[i] == ' ' || palstr[i] == ',' || palstr[i] == '.' ||
        palstr[i] == '!' || palstr[i] == '?') {
      i++;
    }
    palstr[n++] == palstr[i++];
  }

  int j = num;

  i = 0;
  while (i <= num) {
    ans[j--] = palstr[i];
  }
  printf("the reverse of the string %s is %s", palstr, ans);

  if (ans == palstr)
    printf("the string is a palindrome");
  else
    printf("the string is not a palindrome");

  return 0;
}

标签: c

解决方案


有几点需要考虑。首先,关于代码:

if (ans == palstr)

不是你在 C 中比较字符串的方式,它比较的是字符串的地址,在这种情况下总是不同的。

比较字符串的正确方法是:

if (strcmp(ans, palstr) == 0)

其次,您应该在删除所有不需要的字符计算出字符串的长度,因为这是您将使用的长度。我的意思是:

char *src = palstr, dst = palstr;

while (*src != '\0') {
    if (*c != ' ' && *src != ',' && *src != '.' && *src != '!' && *src != '?') {
        *dst++ = *src;
    }
    src++;
}

第三,无论如何,你的while循环中有一个错误,如果你得到两个连续的坏字符,你只会删除第一个(因为你if这样做然后盲目地复制下一个字符)。


第四,您可能需要考虑只删除所有非字母字符而不是那个小选择:

#include <ctype.h>
if (! isalpha(*src) {
    *dst++ = *src;
}

第五也是最后一点,您实际上并不需要创建一个新字符串来检查回文(尽管如果您想反向打印字符串,您可能仍然需要),您可以从两端开始并向内移动,一些喜欢:

char *left = &palstr, right = palstr + strlen(palstr) - 1, ispalin = 1;
while (left < right) {
    if (*left++ != *right--) {
        ispalin = 0;
        break;
    }
}

可能还有其他我错过的事情,但这应该足以开始。


推荐阅读