如何判断一个字符串是不是回文字符串

如题所述

    首先,理解什么是回文字符串,简单的一句话概括就是关于中心左右对称的字符串。例如:ABCBA或者AACCAA是回文字符串;ABCCA或者AABBCC不是回文字符串。

    判断方法就是,依次看两端的字符是否相等。例如:ABCBA,第一个字符与最后一个字符相等,第二个字符与倒数第二个字符相等,第三个字符是中心字符,无需判断。如果是AACCAA就要判断。所以上面的字符串是回文字符串。

    以下是C语言实现判断回文字符串的代码。

#include<stdio.h>

#include<string.h>

int main(void)

{

char s[30];

int b=0;  //1表示不是回文字符串

puts("请输入一个字符串:");

scanf("%s",s);

for(int i=0;i<strlen(s)/2;i++)

if(s[i]!=s[strlen(s)-i-1])

{

b++;

break;

}

if(b)

printf("这不是回文字符串。");

else

printf("这是回文字符串。");

return 0;

}

温馨提示:答案为网友推荐,仅供参考
第1个回答  2014-03-16
#include<iostream.h>
#include<string.h>
class String {
private:
int y;
char *str;
public:
String (char *s);
void huiwen ();
void show ();
};
String::String (char *s){
if (s)
{
str=(char *)new char [strlen(s) 1];
strcpy (str,s);
}
else str = NULL;
}
void String::huiwen (){
if(NULL == str)
cout<<"这个字符串不是回文字符串"<<endl;
char *head = str;
char *tail=str strlen(str)-1;
for (head = &str[0];head<=tail;head ,tail--){
{
if (*head!=*tail)
{
cout<<"这个字符串不是回文字符串"<<endl;
break;
}
if(head 1>=tail)
cout<<"这个字符串是回文字符串"<<'\n';
}
}
//判断str所指向的字符串是否为回文字符串
}
void String::show(){
cout<<str<<endl;
}
void main (){
char s[100]="abffbaf";
String test(s);
test.show();
test.huiwen();
}
第2个回答  2014-03-16
改如下:
void main(void){
int i,j,n;
char a[5];
while(gets(a),*a!='#'){
n=strlen(a);
for(i=0,j=(n-1);i<j;++i,--j){
if(a[i]!=a[j])
break;
}
if(i>=j){
printf("Yes\n");
}
else{
printf("No\n");
}
}
}
相似回答