C语言 判断回文字符串

编写一个名称为fun的函数,功能为判断字符串是否为回文字符串,在main函数中输入字符串,调用fun函数判断所输入的字符串是否为回文字符串。

要求不使用指针,用数组的方法
注意调用fun函数判断,还有最好能用到以下思想:
int i,j,n;
n=strlen(str);
for(i=0,j=n-1;i<=(n-1)/2;i++,j--);
if(str[i]!=str[j]) break;
……
if(i>j)
……
……

第1个回答  2010-04-12
#include <stdio.h>

/*fun()函数:传入一个字符数组,如果是回文序列返回1,不是就返回0*/
int fun(char a[])
{
int i,j,n=0;
while(a[n]!='\0') n++; /*计算传入字符串(数组)长度*/
n--; /*跳出while循环时 a[n]='\0',故n--*/
for(i=0,j=n;i<j;i++,j--)
if(a[i]!=a[j]) break;
if(i>=j) return 1;
return 0;
}

int main()
{
char str[20];
puts("输入一个字符串:\n");
gets(str);
if(fun(str)) printf("%s 是回文序列\n",str);
else printf("%s 不是回文序列\n",str);
return 0;
}
第2个回答  2010-04-11
#include"stdio.h"
panduan(char str[],int count1,int count)/*count1是中间位置,count是字符串个数*/
{
if(str[count1]==str[count-1-count1]&&count1==0)/*递归结束的条件,当0与最后一个相等返回1*/
return(1);
else if(str[count1]==str[count-1-count1])/*当中间的相等,开始向两边移动,当count1为0时结束*/
{
panduan(str, count1-1,count);/*递归*/
}
else
return(0);/*如果不满足条件的话返回0*/

}
void main()
{
char str[20],c;
int i=0,count=0,j,k;
printf("请输入一个字符串\n");
while((c=getchar())!='\n')
{
str[i++]=c;
count++;
}
j=count/2;
k=panduan(str,j,count);
if(k==1)
{
printf("输入的字符串是回文串\n");
}
else
printf("输入的字符串不是回文串\n");
}
第3个回答  2010-04-12
#include<iostream.h>
#include<cstring>
int fun(char *str)
{
int len,half;
len=strlen(str);
half=len/2;
for(int i=0;i<half;i++)
if(str[i]!=str[--len])
break;
if(i>=half)
return 1;
else
return 0;
}
void main()
{char string[1024];
cout<<"please input a string:"<<endl;
cin.getline(string,1024);
if(fun(string))
cout<<"回文字符串"<<endl;
else
cout<<"不是回文字符串"<<endl;
}
第4个回答  推荐于2017-09-05
int fun( char str[] )
{
int i,j,n;
n=strlen(str);

for(i=0,j=n-1;i<=(n-1)/2;i++,j--)
if(str[i]!=str[j]) break;
if(i>j) return 1;
return 0;

}

void main()
{
char a[80];
gets(a);
if ( fun(a)==1 ) printf( "回文\n");
else printf("非回文\n");
}本回答被提问者采纳
相似回答