用递归函数检查给定的字符串是否是回文字符串(boyyob,obo类)

/*用递归函数检查给定的字符串是否是回文字符串*/

#include <stdio.h>

/*声明常量SIZE存储字符串长度,值为50*/

# define SIZE 50

/*声明函数isPalindrome(char[],int n)检验

 *给定的字符串是否是回文字符串

 */

int isPalindrome(char[],int n);

main()

{

       char str[SIZE];

       int n=0,i=0;

       printf("请输入字符串,以回车结束:\n");

       /*先存入第一个字符*/

       scanf("%c",&str[0]);

       /*读取字符直到遇到换行符为止*/

       while(str[i]!='\n')

       {

              scanf("%c",&str[i+1]);

              i=i+1;

              n=n+1;

       }

       if(isPalindrome(str,n))

       {

              printf("该字符串是回文字符串。\n");

       }

       else

       {

              printf("该字符串不是回文字符串。\n");

       }

       return(0);

}

/*定义函数isPalindrome(char[],int n)检验

 *给定的字符串是否是回文字符串

 */

int isPalindrome(char str[],int n)

{

       int i;

       /*当字符串位数少于两位时停止判断*/

       if(n>=2)

       {

              /*判断首尾字符是否相同*/

              if(str[0]!=str[n-1])

                     return 0;

              else

              {

                     /*去掉首尾字符以便继续判断*/

                     for(i=0;i<=n-2;i++)

                     {

                            str[i]=str[i+1];

                     }

                     str[n-2]='\0';

                     return isPalindrome(str,n-2);

              }

       }

       else

              return 1;

}

posted on 2012-06-28 10:09  电脑小白  阅读(675)  评论(0编辑  收藏  举报