电脑看腾讯视频全屏卡:求一c++类,以作参考

来源:百度文库 编辑:中科新闻网 时间:2024/04/28 07:30:11
编写一个MyString类
要求不使用<string.h>等现有的字符串类库,完成以下功能:
字符串的初始化(空构造与拷贝构造)
int SetString(MyString str); 或者 int SetString(char* p);//设定一个字符串的初 始值
char GetAt(int Index); //得到指定位置的字符
int SetAt(int Index, char ch);//设定某一位置的字符(index位置字符为ch)
int Compare(const MyString &str1,const MyString &str1);//字符串比较
char * C_str();//返回C风格的字符串(字符数组)

参靠下MFC的CString吧!

以下是String.h的内容:
class String
{
friend ostream& operator<<(ostream & os, const String& str);
public:
String();
~String();
String(char *cString);
String(const String &string);
String &operator = (const String &sourceStr);
String &operator = (const char *sourceStr);
char GetAt(int index);
bool SetAt(int index, const char ch);
int CompareTo(const String& anotherString);
char * C_str(){return cString;}
int GetLength()const{return length(cString);}
private:
int length(const char * cStr)const;
void copy(const char* from, char *to);
public:
char *cString;
};

以下是String.cpp的内容:
#include<iostream.h>
#include<assert.h>
#include "String.h"

int main()
{
String str1("asfkkkk");
String str2 = "jsfkkkk";
cout<<str1<<"\t"<<str2<<endl;
cout<<str1.CompareTo(str2);
str1 = str2;
cout<<endl<<str1<<"\t"<<str1.GetLength();
str1.SetAt(6, 'g');
cout<<endl<<str1<<"\t"<<str1.GetLength();
return 0;
}

ostream& operator<<(ostream &os, const String& str)
{
os<<str.cString;
return os;
}

String::String()
{
cString = new char[1];
cString[0] = '\0';
}

String::String(char * rcString)
{
cString = new char[length(rcString) + 1];
copy(rcString, cString);
}

String::String(const String &string)
{
operator=(string);
}

String::~String()
{
delete []cString;
}

int String::length(const char *cStr)const
{
int count = 0;
const char * pointer;
if(cStr)
{
pointer = cStr;
while(*pointer++)
count++;
}
return count;
}

void String::copy(const char* from, char *to)
{

assert(from!=NULL && to!=NULL);

const char * pfrom = from;
char * pto = to;
char temp;
while((temp = *pfrom++) != '\0')
*pto++ = temp;
*pto = '\0';

}

int String::CompareTo(const String& anotherString)
{
char * po = anotherString.cString;
char * pthis = cString;
char co, cthis;
co = *po++;
cthis = *pthis++;
while(co != '\0' && cthis != '\0' && co==cthis)
{
co = *po++;
cthis = *pthis++;
}
int result = (int)(cthis - co);
if(result < 0)
return -1;
else if(result > 0)
return 1;
else
return 0;
}
char String::GetAt(int index)
{
assert(length(cString) > index && index>=0);
return cString[index];
}

String & String::operator= (const String &sourceStr)
{
if(cString)
delete [] cString;
cString = new char[sourceStr.GetLength() + 1];
copy(sourceStr.cString, cString);
return *this;
}

bool String::SetAt(int index, const char ch)
{
assert(length(cString) > index && index>=0);
cString[index] = ch;
return true;
}

String &String::operator = (const char *sourceStr)
{
if(cString)
delete [] cString;
cString = new char[length(sourceStr) + 1];
copy(sourceStr, cString);
return *this;
}