定义一个cstring类,实现字符串的操作例如strcpy,strcmp,strlen,strcat 10

只能调用自定义函数,标准的c++输入输出,应用面向对象的封装,继承,多太态技术要有界面设计... 只能调用自定义函数,标准的c++输入输出,应用面向对象的封装,继承,多太态技术
要有界面设计
展开
 我来答
terranlong
2012-02-27 · TA获得超过7294个赞
知道大有可为答主
回答量:2660
采纳率:0%
帮助的人:3994万
展开全部
不需要用到继承、多态。界面就不设计了,累。能看明白就行
#include <iostream>
using namespace std;

class cstring
{
public:
cstring():buffer(NULL),length(0){}
cstring(const cstring& cstr)
{
int i;
buffer = new char[cstr.length + 1];
for (i = 0; i < cstr.length; i++)
{
buffer[i] = cstr.buffer[i];
}
buffer[i] = '\0';
length = cstr.length;
}
cstring(char* str):length(0)
{
char* p = str;
int i;
while (*p)
{
length++;
p++;
}
buffer = new char[length + 1];
for (i = 0; i < length; i++)
{
buffer[i] = str[i];
}
buffer[i] = '\0';
}
~cstring()
{
if (length != 0)
{
delete []buffer;
}
}
void strcpy(cstring cstr);
int strcmp(cstring cstr);
int strlen();
cstring strcat(cstring cstr);
cstring& operator =(const char* str);
cstring& operator =(const cstring cstr);
friend ostream& operator <<(ostream& os, const cstring cstr);
private:
char* buffer;
int length;
};

void cstring::strcpy(cstring cstr)
{
delete []buffer;
*this = cstr;
}

int cstring::strlen()
{
return length;
}

int cstring::strcmp(cstring cstr)
{
char* p1 = buffer;
char* p2 = cstr.buffer;
while (*p1 && *p2)
{
if (*p1 > *p2)
{
return 1;
}
else if (*p1 < *p2)
{
return -1;
}
p1++;
p2++;
}
if (*p1)
{
return 1;
}
else if (*p2)
{
return -1;
}
return 0;
}

cstring cstring::strcat(cstring cstr)
{
cstring des_cstr(*this);
int i;
delete []buffer;
buffer = new char[length + cstr.length + 1];
for (i = 0; i < length; i++)
{
buffer[i] = des_cstr.buffer[i];
}
for (i = 0; i < cstr.length; i++)
{
buffer[length + i] = cstr.buffer[i];
}
buffer[length + i] = '\0';
length += cstr.length;
return *this;
}

cstring& cstring::operator =(const char* str)
{
int len = 0;
int i;
char* p = (char*)str;
while (*p)
{
len++;
p++;
}
buffer = new char[len + 1];
for (i = 0; i < len; i++)
{
buffer[i] = str[i];
}
buffer[i] = '\0';
length = len;
return *this;
}

cstring& cstring::operator =(const cstring cstr)
{
*this = cstr.buffer;
return *this;
}

ostream& operator <<(ostream& os, const cstring cstr)
{
os << cstr.buffer;
return os;
}

int main()
{
cstring s1 = "abc";
cstring s2 = "def";
cout << "s1=\"" << s1 << "\" s2=\"" << s2 << "\"" << endl;
cout << "strcpy:" << endl;
s1.strcpy(s2);
cout << "s1=\"" << s1 << "\" s2=\"" << s2 << "\"" << endl;
cout << "s1.strcmp(s2)=" << s1.strcmp(s2) << endl;
cout << "s1.strlen()=" << s1.strlen() << endl;
cout << "strcat:" << endl;
s1.strcat(s2);
cout << "s1=" << s1 << endl;
return 0;
}
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式