32.定义一个字符串类 String,实现判断该字符串是否为回文字符串。所谓回文字符串,是指该字符串左右对称。例如字符串“123321”是回文字符串。
具体要求如下:
- 私有数据成员
- char *str;
- int flag:标记是否为回文字符串。
- 公有成员函数
- String (char *s) ;构造函数,用给定的参数s初始化数据成员 str。flag初始化为0。
- void huiwen ();判断 str 所指向的字符串是否为回文字符串。
- void show();在屏幕上显示字符串。
- 在主程序中定义字符串 char s[]=”ababcedbaba”作为原始字符串。定义一个 String 类对象 test,用s 初始化 test,完成对该类的测试。
#include<iostream>
#include<cstring>
using namespace std;
class String{
char *str;
int flag;
public:
String(const char *s){
flag=0;
str=new char[strlen(s)+1];
strcpy(str,s);
}
void fun(){
char *p1=str,*p2=str+strlen(str)-1;
while(p1<=p2&&*p1==*p2){
p1++;
p2--;
}
if(p1>p2)flag=1;
}
void show(){
cout<<str<<endl;
fun();
cout<<"flag="<<flag<<endl;
}
};
int main(){
String s1("ababcedbaba"),s2("aabbccbbaa"),s3("aabbcacbbaa");
s1.show();
s2.show();
s3.show();
return 0;
}