c - 使用 C 进行反向字符串比较

标签 c

<分区>

我刚刚编译了这个程序,但它似乎不起作用。

我应该做的是编写一个程序来确定一个单词是否为回文(前后相同的单词,例如“racecar”或“eye”)。

它还应该忽略大小写字母(例如 Racecar 或 eYe)。这是我目前所拥有的:

int main()

    char word[21],reverse[21];
    printf("Type a word and I will tell you if it is a Palindrome: ");
    fgets(word,21,stdin);
    puts("");
    printf("The word that you typed is: %s \n",word);
    strcpy(reverse,word);
    strrev(reverse);
    if((strcmp(reverse,word))==0)
    printf("This word is a palindrome");
    else
    printf("This word is NOT a palindrome");

    return 0;
}

最佳答案

您不需要反转字符串来检查它是否是回文,而且 strrev 不是 C 标准中的函数。您可以只检查单词的开头和结尾:

char word[21];
printf("Type a word and I will tell you if it is a Palindrome: ");
fscanf(stdin, "%s", word);
puts("");
printf("The word that you typed is: %s \n",word);

size_t len = strlen(word);
int s;
bool palindrome = true;
for (s = 0; s < len / 2; s++) {
    if (tolower(word[s]) != tolower(word[len-1-s])) {
        palindrome = false;
        break;
    }
}
if(palindrome)
    printf("This word is a palindrome");
else
    printf("This word is NOT a palindrome");

这节省了空间和时间。

关于c - 使用 C 进行反向字符串比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36905110/

相关文章:

c - 尝试使用线程在 C 中按顺序打印数字

c++ - 苹果系统。如何从 PNG 数据创建图像?

c++ - 哪个 GUI 库用于开发 Mozilla Firefox?

c - 这个复杂的 C 类型声明是什么意思?

c - 使用 BIO_printf() 而不是 printf() 有什么好处?

c++ - 检测是否同时按下 2 个键

c - Linux 和实时信号

c - 如何在C中的窗口上显示两个位图图像

c - 在不知道其类型的情况下,释放为指向指针的指针分配的所有空间

c++ - 无法通过Visual Studio在cpp文件中构建devlib库函数