c - 检查非对称回文
问题描述
我已经为 myprogramminglab 赋值编写了一个程序,它应该接受一个字符串输入,检查它是否是回文,然后输出结果。
我所拥有的是除了一项测试之外的所有工作。“一个人计划巴拿马运河”是一个回文,但我的程序说它不是。我认为这一定是因为程序将第二个空格与“巴拿马”中的“m”进行了比较。
另一方面,“我能在我看到厄尔巴岛”被捕获为回文,但我猜这是因为它是对称的,并且在左侧跳过一个空格与在左侧跳过一个空格同时发生正确的。
#include <stdio.h>
#include <stdlib.h>
int is_not_alnum(char c);
int testPalindrome(const char string[], int begin, int end);
int main (void)
{
int n;
char temp;
printf("Enter the size of your string: ");
scanf("%d" , &n);
char string[n];
printf("Enter your string to check if it is a palindrome: ");
scanf("%c",&temp);
scanf("%[^\n]" , string);
if(testPalindrome(string, 0 , n - 1))
printf("\"%s\" is a Palindrome.\n" , string);
else
printf("\"%s\" is not a Palindrome.\n" , string);
//puts("");
return(0);
}
//program only needs to worry about lowercase and 0-9 alphanumeric
int is_not_alnum(char c)
{
if( ((c >= 'a') && (c <= 'Z')) || ((c >= '0') && (c <= '9')) )
return(0);
else
return(1);
}
int testPalindrome(const char string[], int begin, int end)
{
while (begin <= end)
{
if(is_not_alnum(string[begin]))
begin++;
if(is_not_alnum(string[end]))
end--;
if(string[begin] == string[end])
{
return(testPalindrome(string , begin++ , end--));
return(1);
}
else
return(0);
}
}
解决方案
您正在检查大写字符“Z”,它应该是:
#include <stdio.h>
#include <stdlib.h>
int is_not_alnum(char c);
int testPalindrome(const char string[], int begin, int end);
int main (void)
{
int n;
char temp;
printf("Enter the size of your string: ");
scanf("%d" , &n);
char string[n];
printf("Enter your string to check if it is a palindrome: ");
scanf("%c",&temp);
scanf("%[^\n]" , string);
if(testPalindrome(string, 0 , n - 1))
printf("\"%s\" is a Palindrome.\n" , string);
else
printf("\"%s\" is not a Palindrome.\n" , string);
//puts("");
return(0);
}
//program only needs to worry about lowercase and 0-9 alphanumeric
int is_not_alnum(char c)
{
if( ((c >= 'a') && (c <= 'z')) || ((c >= '0') && (c <= '9')) )
return(0);
else
return(1);
}
int testPalindrome(const char string[], int begin, int end)
{
if (begin <= end)
return(1);
if(is_not_alnum(string[begin]))
begin++;
if(is_not_alnum(string[end]))
end--;
if(string[begin] == string[end])
{
return(testPalindrome(string , begin++ , end--));
}
else
return(0);
}
推荐阅读
- php - API 调用中未收到 POST 数据
- javascript - 如何在 php 中获取表单字段的值(字段是从 javascript 创建的)?
- html - Bannermover 的第一个 img 不直接跟在 bannermove 的最后一个 img 之后
- android - 当外部存储空间不足时,DownloadManager 不广播意图
- html - 移动网站背景图片未调整大小
- c - 有什么方法可以让我的函数更快地测试字符串的相等性?
- python - 如何获取 Pandas 索引位置和名称
- angular - Ionic 4 应用程序无法在 android Lollipop 中运行
- php - 将毫秒转换为分钟:得到不正确的结果
- html - Required attribute in multi step form