greenpeace is global:请教c++高手!用c++编写一个字符串程序

来源:百度文库 编辑:神马品牌网 时间:2024/05/09 08:21:34
设计一个字符串类,功能如下:
1) 能够用 “+” 来处理两个字符串的相加
2) 具有在一个字符串中搜索一个字符的功能
3) 具有在一个字符串中搜索另一个字符串的功能
4) 编写一个main()函数,测试你的字符串类的各种功能。

请在两天内提供c++程序.感激不尽!

+操作没什么好说的;
FindChar返回的是第一次出现字符的位置;
FindString返回的是第一次出现字符串的位置也可以返回指针;

我调试过了这次没有问题了,满意吗?

#include "stdio.h"
#include "string.h"
class Str
{
public:
Str();
Str(char *s);
~Str();
friend char* operator+ (Str &res, Str &dec);
int FindChar(char ch);
int FindString(char *s);

private:
char *val;
};
Str::Str()
{
val=NULL;
}
Str::Str(char *s)
{
int i=0;
while(s[i]!='\0') i++;
val=new char[i];
sprintf(val,"%s",s);
}
Str::~Str()
{
// if(val!=NULL) delete val;
}

char* operator+ (Str &res, Str &dec)
{
return (strcat(res.val,dec.val));
}
int Str::FindChar(char ch)
{
if(val[0]==NULL) return -1;
int i=0;
while(val[i++]!='\0')
if(val[i]==ch) break;
return i;
}

int Str::FindString(char *s)
{
return (int)(strstr(val,s)-val);
}

void main()
{
Str a("abcdefghijklmnopqrstuv"),b("xyz");
char ch='u';
printf("%s\n",a+b);
printf("%d\n",a.FindChar(ch));
printf("%d\n",a.FindString("xyz"));
}