我必须编写一个程序来检查字符串是否是回文。 回文序列是向前和向后相同的序列。 例如,皮艇是回文,独木舟不是回文,汉娜是回文等。
到目前为止,这是我的代码:
#include <stdio.h>
#include <string.h>
#define MAX_CHAR 4096
int main(void) {
printf("Enter a string: ");
char line[MAX_CHAR] = {0};
fgets(line, MAX_CHAR, stdin);
int length = strlen(line) - 1;
int i = 0;
int j = length - 1;
char line2[length];
while (i < length){
if (j >= 0){
line2[i] = line[j];
}
i++;
j--;
}
if (strcmp(line, line2) != 0){
printf("String is not a palindrome\n");
} else if (strcmp(line, line2) == 0) {
printf("String is a palindrome\n");
}
return 0;
}
这适用于非回文,但每次我用回文测试时,我都会收到运行时错误,如image所示。 我该如何解决这个问题?
答案 0 :(得分:1)
您面临的问题是由于您没有向type: "param"
添加空终结符(并且数组也没有足够的空间),因此line2
不是以空字符结尾的字节字符串。
将指向除以空字符结尾的字节字符串以外的任何内容传递给strcmp
将调用未定义的行为
修复代码的最简单方法是进行以下更改:
line2
请注意,有更简单的方法可以实现回文检查,但这个答案只关注你的代码遇到运行时错误的原因。
编辑:正如评论fgets
中所指出的,还将换行符存储在数组中。为了使您的回文检查正常工作,您需要调整代码(例如:在创建/* Don't subtract 1 from `strlen`, otherwise you don't copy the entire string in your loop */
int length = strlen(line);
/* Unchanged */
int i = 0;
int j = length - 1;
/* increase size of array by 1 to have space for null-terminator */
char line2[length + 1];
/* Loop is unchanged */
while (i < length){
if (j >= 0){
line2[i] = line[j];
}
i++;
j--;
}
/* Add null-terminator to have a valid byte string */
line2[length] = '\0';
之前从line
删除换行符并复制字符)
答案 1 :(得分:-1)
更简单的方法:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int palindrome(const char *word)
{
size_t len = strlen(word);
const char *end = word + len -1;
len >>= 1;
while(len--)
{
if(*word++ != *end--)
return 1; //not
}
return 0; //yes;
}
int main()
{
printf("%s\n", palindrome("kayak") ? "No" : "Yes");
}
答案 2 :(得分:-1)
您有错误的边界检查,并且fgets还会读取您必须删除的换行符。这是唯一能够检查输入的字符串是否为空的竞争答案:
#include <string.h>
#define MAX_CHAR 4096
int main(void) {
printf("Enter a string: ");
char line[MAX_CHAR] = {0};
fgets(line, MAX_CHAR, stdin);
//remove new line
int length = strlen(line);
if (length > 0) {
line[length-1] = '\0';
}
//update length
length = strlen(line);
if (!length) {
printf("String is empty\n");
return 1;
}
int i = 0;
int j = length - 1;
char line2[length+1];
while (i < length){
line2[i++] = line[j--];
}
//Add 0 char
line2[i] = '\0';
if (strcmp(line, line2) != 0){
printf("String is not a palindrome\n");
} else if (strcmp(line, line2) == 0) {
printf("String is a palindrome\n");
}
return 0;
}