C++面向对象编程题 第32题

32.定义一个字符串类 String,实现判断该字符串是否为回文字符串。所谓回文字符串,是指该字符串左右对称。例如字符串“123321”是回文字符串。
具体要求如下:

  1. 私有数据成员
  • char *str;
  • int flag:标记是否为回文字符串。
  1. 公有成员函数
  • String (char *s) ;构造函数,用给定的参数s初始化数据成员 str。flag初始化为0。
  • void huiwen ();判断 str 所指向的字符串是否为回文字符串。
  • void show();在屏幕上显示字符串。
  1. 在主程序中定义字符串 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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值