[英]C Program to check if string is Palindrome or not
我的C程序有些掙扎! 它應該檢查字符串是否是回文式! 它不應該注意非字母字符,因此程序應將其識別為回文! “他過着魔鬼的生活,是嗎?” 那就是我到目前為止所得到的:
#include <stdio.h>
#include <stdlib.h>
int main()
{
char sentence[39];
int left = 0;
int right = 40;
printf("Enter a message: ");
fgets(sentence, 40, stdin);
while(1) {
while(left < right && !(isalpha(sentence[left])))
left++;
while(right > left && !(isalpha(sentence[right])))
right--;
if(left >= right)
break;
else {
if(sentence[left] != sentence[right]) {
printf("Not a Palindrome");
return 0;
}
left++;
right--;
}
}
printf("Palindrome");
return 0;
}
它總是在打印:不是回文! 即使是一個。
我對您的程序進行了一些更改。 首先不破壞數組索引,其次使用字符串長度而不是訪問未定義的值,第三次檢查相同的大小寫字母。
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main()
{
char sentence[200]; // provide plenty of room
int left = 0;
int right; // do not assume the length
printf("Enter a message: ");
fgets(sentence, sizeof sentence, stdin); // limit the input
right = strlen(sentence); // now get the length
while(1) {
while(left < right && !(isalpha(sentence[left])))
left++;
while(right > left && !(isalpha(sentence[right])))
right--;
if(left >= right)
break;
else {
if(toupper(sentence[left]) != toupper(sentence[right])) { // get case the same
printf("Not a Palindrome\n");
return 0;
}
left++;
right--;
}
}
printf("Palindrome\n");
return 0;
}
計划會議:
Enter a message: He lived as a devil, eh? Palindrome Enter a message: palindrome Not a Palindrome
您可以編寫一個單獨的函數來檢查輸入的句子是否是回文。
至於你的代碼,那么這些語句
char sentence[39];
int left = 0;
int right = 40;
printf("Enter a message: ");
fgets(sentence, 40, stdin);
導致不確定的行為,因為在嘗試輸入40個字符時,數組語句只有39個元素。 同樣,輸入的字符串的字符數不能超過40個字符。 您需要確定字符串的長度。
這是一個演示程序,顯示了如何編寫相應的函數。
#include <string.h>
#include <ctype.h>
#include <stdio.h>
int is_palindrome(const char *s)
{
size_t n = strlen(s);
const char *first = s, *last = s + n;
if (n)
{
do
{
while ( *first && !isalpha((unsigned char)*first)) ++first;
if (first != last)
{
while (!isalpha((unsigned char)*--last));
}
} while ( toupper( ( unsigned char )*first ) ==
toupper( ( unsigned char )*last ) &&
first != last &&
++first != last);
}
return first == last;
}
#define N 100
int main()
{
while (1)
{
char s[N];
printf("Enter a sentence (Enter - exit): ");
if (!fgets(s, sizeof(s), stdin) || s[0] == '\n') break;
printf("\nThe sentence is%s palindrome.\n\n",
is_palindrome(s) ? "" : " not");
}
return 0;
}
它的輸出可能看起來像
Enter a sentence (Enter - exit): He lived as a devil, eh
The sentence is palindrome.
Enter a sentence (Enter - exit):
您應該將right初始化為字符串的結尾:
#include <string.h>
// ...
right = strlen(sentence) - 1;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.