猿问

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

设计你自己的字符串类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类,然后实现以上函数,谢谢!!

翻阅古今
浏览 383回答 2
2回答

POPMUISE

//测试程序如下#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;}
随时随地看视频慕课网APP
我要回答