简体   繁体   English

C中的回文检查器

[英]Palindrome Checker in C

Where should I include toupper() in my code in order to make a palindrome such as Noon or NoOoON to say it is a palindrome rather than saying it is not a palindrome. 我应该在我的代码中包括toupper(),以便使像Noon或NoOoON这样的回文表明它是回文而不是说它不是回文。 I can't seem to figure it out. 我似乎无法弄明白。 Thanks. 谢谢。

#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; 
}

In your case, you can just use _stricmp instead of strcmp . 在您的情况下,您可以使用_stricmp而不是strcmp

Another way to approach this is to convert your string to a single case after it is input. 另一种方法是在输入后将字符串转换为单个大小写。 eg 例如

for (char *c = a; *c; c++) *c = toupper(*c);

If you want to use toupper() then you should apply it before you make a copy of the string and reverse it. 如果你想使用toupper()你应该在复制字符串之前应用它并反转它。

That is: 那是:

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);

If you convert the string to a single case later, then the copy will not be the same as the original, or you'd have to toupper() both. 如果稍后将字符串转换为单个案例,则副本将与原始字符串不同,或者您必须同时使用toupper()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM