c - 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;
}
解决方案
有几点需要考虑。首先,关于代码:
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;
}
}
可能还有其他我错过的事情,但这应该足以开始。
推荐阅读
- docker - 用于构建 CUDA 的 Repo2docker 启用了 Docker 映像
- python - 如何通过对数据框中的另一列进行排序来返回一列的总和?
- python - 多元时间序列模型的输入维度
- python - 为什么 DPI 信息返回为 (1,1) 而图像属性显示为 (96,96)?
- android - RoomLibrary - 当前 JDK 版本 1.8.0_221-b11 有一个错误 (https://bugs.openjdk.java.net/browse/JDK-8007720) 阻止 Room 增量
- lua - 罗技游戏软件宏脚本问题
- r - 如何在小时之间添加值
- python - 基于不同行条件的新数据框列
- c# - Google Play 游戏服务保存的游戏:自上次修改属性以来的时间?
- visual-studio-code - Visual Studio Code 选项卡快捷方式