【发布时间】:2020-12-02 23:19:42
【问题描述】:
我尝试编写 C 程序,用户可以在其中输入字符串,程序应该检查字符串是否为回文。该字符串也可以是诸如“没有柠檬,没有甜瓜”之类的句子。我有一个函数“checkForSpaceAndChar”从句子中删除空格,另一个函数“isPalindrome”检查字符串是否为回文。现在我尝试弄清楚如何首先获取输入的字符串并删除空格和特殊字符,然后检查该字符串是否为回文。
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <ctype.h>
#include <string.h>
int isPalindrome(char inputeString[]){
int begin = 0, end = strlen(inputeString) - 1;
while (end > 1) {
if (inputeString[begin++] != inputeString[end--]) {
return 0;
}
else {
return 1;
}
}
}
char checkForSpaceAndChar(char stringWithoutSpace[], char newArray[]) {
for (int i = 0; i < strlen(stringWithoutSpace); i++) {
if (isalpha(stringWithoutSpace[i]) != 0) {
stringWithoutSpace[i] = newArray[i];
}
}
}
#define SIZE 1000
int main(void) {
int repeat = 1;
char arrayPalindrome[SIZE], newArray[SIZE];
while (repeat == 1) {
printf("Enter a sentence: ");
scanf("%s", arrayPalindrome);
checkForSpaceAndChar(arrayPalindrome, newArray);
if (isPalindrome(arrayPalindrome) == 0) {
printf("This sentence is not a palindrome.");
}
if (isPalindrome(arrayPalindrome) == 1) {
printf("This sentence is a palindrome.");
}
printf("\n\nDo you want to enter another sentence (0 for no, 1 for yes)?");
scanf_s("%d", &repeat);
}
return 0;
}
【问题讨论】:
-
你已经描述了你想要做什么,但你没有描述你对所示代码有什么具体的错误或问题。
-
isPalindrome()不正确。它总是在循环的第一次迭代期间返回,因此它只检查第一个字符是否与最后一个字符相同。return 1应该在循环之后,而不是在else中。 -
OT:两次调用
isPalidrome效率低下。只需调用一次并保存返回值。尽管在这种情况下,使用if () { ..} else { .. }而不是检查返回值两次更为常见。 -
scanf("%s")与gets有相同的问题。永远不要使用gets。 stackoverflow.com/questions/1694036/… 作为直接推论,永远不要使用scanf("%s"...) -
关于:
for (int i = 0; i < strlen(stringWithoutSpace); i++) {函数:strlen()返回一个size_t,它是一个无符号值。该语句将其与int进行比较,这是一个有符号值。
标签: c c-strings palindrome function-definition