我必须做一个程序,告诉我一个字符串是回文还是不使用库字符串。我写了下面的代码,但是输出总是“回文”

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

int main()
{
 char a[100],b[100];
 int i,k;
 printf("Type the string \n");
 gets(a);
 k=strlen(a);
 for(i=0;i<strlen(a);i++)
 {
  a[i]=b[k];
  k--;
 }           //at the end of this code the string "b" should be the reverse of "a"
 k=strcmp(a,b);
 if (k!=0)   //here I check if a=b or not
 {printf("palindrome");}
 else
 {printf("not palindrome");}
 getch();
 return 0;
}

示例:当我的输入为“non”时,输出应为“palindrome”,如果输入为“ship”,则输出应为“not palindrome”。有人能帮我找出哪里不对劲吗?

最佳答案

我想是这条线
a[i]=b[k];
这是否将b[k](您尚未初始化)的内容放入a[i](您已经用get填充了)中?这会用空格覆盖a中的测试值(或者b内存中的任何内容),难道你不应该做相反的事情吗?
但最好不要这样做-你可以比较数组中的字符。

k=strlen(a);
for(i=0; i<k/2; i++)
   if(a[i] != a[k-i])
      return "Not Palindrome";
return "Palindrome";

09-04 03:24