[英]Palindrome Checker in C
我應該在我的代碼中包括toupper(),以便使像Noon或NoOoON這樣的回文表明它是回文而不是說它不是回文。 我似乎無法弄明白。 謝謝。
#include <stdio.h>
#include <string.h>
#include <ctype.h>
void reverse(char s[]){
int c, i , j;
for (i = 0, j = strlen(s)-1; i < j; i++, j--) {
c = s[i];
s[i] = s[j];
s[j] = c;
}
return;
}
int main(){
char a[20];
char b[20];
printf("Enter a string:\n");
gets(a);
strcpy(b,a); // copies string a to b
reverse(a); // reverses string b
if(strcmp(a, b) == 0) { // compares if the original and reverse strings are the same
printf("The string is a Palindrome\n");
}
else {
printf("The string is not a Palindrome\n");
}
return 0;
}
在您的情況下,您可以使用_stricmp
而不是strcmp
。
另一種方法是在輸入后將字符串轉換為單個大小寫。 例如
for (char *c = a; *c; c++) *c = toupper(*c);
如果你想使用toupper()
你應該在復制字符串之前應用它並反轉它。
那是:
int main() {
char a[20];
char b[20];
int i = 0;
printf("Enter a string:\n");
gets(a);
// make the change here
for (i = 0; i < strlen(a); i++) {
a[i] = toupper(a[i]);
}
strcpy(b, a);
如果稍后將字符串轉換為單個案例,則副本將與原始字符串不同,或者您必須同時使用toupper()
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.