打印

字符串比较问题

[复制链接]
1093|1
手机看帖
扫描二维码
随时随地手机跟帖
跳转到指定楼层
楼主
hsbjb|  楼主 | 2012-6-7 17:19 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
#include<iostream>
#include<string>
using namespace std;
class CMystring
{
public:
CMystring(char *);
int length(); //求长度
int compare(CMystring &); //两个字符串比较
private:
char * str;
}
CMystring::CMystring(char*p)
{
str=p;
}

int CMystring::length()
{
int len=0;
while(*str!='\0')
{
str++;
len++;
}
return len;
}

int CMystring::compare(CMystring & pp)
{
if(this->length()>pp.length())
{
return 1;
}
else if(this->length()<pp.length())
{
return -1;
}
else
{
return 0;
}

}
int main()
{
CMystring c1("good");
CMystring c2("better");
cout<<c1.length()<<endl; //输出c1的长度
cout<<c2.length()<<endl; //输出c2 的长度
cout<<c1.compare(c2)<<endl;
return 0;
}
在测试字符串的比较时错了,却找不出原因,求帮忙,谢谢

相关帖子

沙发
baidudz| | 2012-6-7 20:29 | 只看该作者
你做length的时候改变了str的指向,用个临时的变量代替一下

char* strTemp = str;
int len=0;
while(*strTemp !='\0')
{
strTemp ++;
len++;
}
return len;

使用特权

评论回复
发新帖 我要提问
您需要登录后才可以回帖 登录 | 注册

本版积分规则

193

主题

2354

帖子

0

粉丝