为了账号安全,请及时绑定邮箱和手机立即绑定

使用C++ 该如何实现MyString类 ?有什么更好的办法吗?

使用C++ 该如何实现MyString类 ?有什么更好的办法吗?

翻阅古今 2021-06-28 11:07:02
设计你自己的字符串类MyString1,并实现下面函数:MyString1();MyString1(char *chars);MyString1(char char[], int size);MyString1 append(MyString1 s);MyString1 append(MyString1 s, int index, int n);MyString1 assign(char chars[]);MyString1 assign(MyString1 s, int index, int n);char at(int index);int length();void clear();MyString1 erase(int index, int n);//删除当前从index开始的n个字符bool empty();int compare(MyString1 s);请写出MyString类,然后实现以上函数,谢谢!!
查看完整描述

2 回答

?
POPMUISE

TA贡献1765条经验 获得超5个赞

//测试程序如下
#include "stdafx.h"
#include <fstream>
#include <iostream>
#include <iterator>
#include <sstream>
#include <cstdlib>
using namespace std;
class Mystring
{
private:
char *a;
int len;
public:
Mystring()
{
len=0;
}
Mystring(char* s)
{
len=strlen(s);
a=new char[len+1];
memcpy(a,s,len+1);
}
void input() //输入任意长度的字符串
{
char *p = new char[len], ch;
int i = 0;
len = 16;
while(cin>>ch)
{
if(i >= len)
{
char *q = new char[len *= 2];
memcpy(q, p, i);
delete []p;
p = q;
}
p[i++] = ch;
}
len = i;
a = p;
}
void join(const Mystring &s) //在字符串尾部连接上s
{
if(s.len < 1)
return;
int t = s.len + len;
char *q = new char[t]();
memcpy(q, a, len);
memcpy(q+len, s.a, s.len);
a = q;
len = t;
}
~Mystring() //析构函数
{
if(len)
{
delete []a;
a = NULL;
len = 0;
}
}
void Mystring::output()
{
//输出字符串
if(len==0)
cout<<"该字符串为空!"<<endl;
else
{
for(int i = 0; i < len; i++)
{
cout<<a[i];
}
}
}
int Mystring::length()
{
return len;
}
};
void main()
{
// 类Mystring的测试程序
Mystring s1;
cout<<"字符串s1为:";
s1.output();
cout<<"字符串s1的长度为:"<<s1.length()<<endl;
cout<<"请输入一个字符串:";
s1.input();
cout<<"字符串s1为:";
s1.output();
cout<<"字符串s1的长度为:"<<s1.length()<<endl;
Mystring s2("hello!");
cout<<"字符串s2为:";
s2.output();
cout<<"字符串s2的长度为:"<<s2.length()<<endl;
s1.join(s2);
cout<<"连接s2后字符串s1为:";
s1.output();
cout<<"字符串s1的长度为:"<<s1.length()<<endl;
s2.join(s1);
cout<<"连接s1后字符串s2为:";
s2.output();
cout<<"字符串s2的长度为:"<<s2.length()<<endl;
}



查看完整回答
反对 回复 2021-07-04
  • 2 回答
  • 0 关注
  • 382 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信