geekdoc-python-zh/docs/overiq/122.md

2.6 KiB
Raw Permalink Blame History

C 程序:检查一个字符串是否是回文

原文:https://overiq.com/c-examples/c-program-to-check-whether-a-string-is-palindrome-or-not/

最后更新于 2020 年 7 月 27 日


[no_toc]

什么是回文?

一个数字或一个单词即使被颠倒了也保持不变,叫做回文。比如妈妈,雷达,或者数字 45654都是回文。

下面是一个判断一个字符串是否是回文的 C 程序。

/*******************************************************
 Program to check whether a string is palindrome or not
 * 
 * Enter a word: racecar
 * racecar is palindrome
 *******************************************************/

#include<stdio.h> // include stdio.h library
#include<string.h> // include stdio.h library

int main(void)
{       

    int len, i= 0, j, is_palindrome = 1;

    char word[50];

    printf("Enter a word: ");
    scanf("%s", word);

    j = strlen(word) - 1;  // get the last valid index

    while(i <= j)
    {
        if (word[i] != word[j])
        {
            is_palindrome = 0;
            break;
        }

        i++;  
        j--;
    }

    if(is_palindrome)
    {
        printf("%s is palindrome", word);
    }
    else
    {
        printf("%s is not palindrome", word);
    }

    return 0;
}

**预期输出:**第一次运行:

Enter a word: racecar
racecar is palindrome

第二次运行:

Enter a word: netbeans
netbeans is not palindrome

相关程序: C 程序检查数字是否为回文

它是如何工作的

下表演示了 while 循环每次迭代时发生的情况,假设word = radar

循环 情况 j
第一次迭代后 word[0]!=word[1]=>'r'!='r'=>0 i=1 j=3
第二次迭代后 word[1]!=word[3]=>'a'!='a'=>0 i=2 j=2
第三次迭代后 word[2]!=word[2]=>'d'!='d'=>0 i=3 j=1

因此,字符串radar是回文。


推荐阅读: