求助
本帖最后由 风之残月 于 2014-11-10 10:24 编辑1. 设计一个具有如下功能的简单字符串类,并写出其驱动函数(main函数)。(1)设置新的字符串(SetS());(2)返回字符串(getS());(3)从字符串中获取并返回任意子串(getSubS());(4)获取并返回字符串中指定位置的字符(getC());(5)返回字符串长度(strLen())。提示:字符串类至少应包含两个属性(数据成员):contex用来存放任意字符序列(可以用字符数组或字符指针),strlen用来存放字符串的长度(字符个数);
要求用C++实现。求帮助。不够可以追加悬赏。 #include <iostream>
#include <cstring>
#include <cassert>
using namespace std;
class MyString {
public:
MyString(){
MakeEmptyString();
}
~MyString() {
delete[] contex;
}
void SetS( const char* str );
const char* getS()const { return contex; }
MyString getSubS( int start_pos, int length )const;
char getC( int pos ) const {
assert( pos>=0 && pos<strlen );
return contex;
}
char& getC( int pos ) {
assert( pos>=0 && pos<strlen );
return contex;
}
unsigned int strLen() const { return strlen; }
MyString( const MyString& str ) {
MakeEmptyString();
SetS( str.contex );
}
MyString& operator=( const MyString& str) {
if( this == &str ) return *this;
SetS( str.contex );
}
private:
char* contex;
unsigned int strlen;
void MakeEmptyString() {
contex = new char;
strlen = 0;
contex=0;
}
};
void MyString::SetS( const char* str ) {
if( contex != str ) {
strlen = ::strlen(str);
delete[] contex;
contex = new char;
strcpy( contex, str );
}
}
MyString MyString::getSubS( int start_pos, int length )const {
assert( start_pos>0 && start_pos<strlen );
assert( length >0 && start_pos + length < strlen );
MyString result;
char * ptmp = new char[ length+1 ];
for( int i=0;i<length; ++i ) ptmp = contex;
ptmp=0;
result.SetS(ptmp);
return result;
}
int main() {
MyString str;
cout<<"empty str:"<<str.getS()<<endl;
str.SetS("0123456789");
cout<<"Set str:"<<str.getS()<<endl;
cout<<"Sub String from pos 2,length 3 is:"<<str.getSubS(2,3).getS()<<endl;
cout<<"str is:"<<str.getC(6)<<endl;
str.getC(6) = 'a';
cout<<"after str.getC(6) = 'a', str is:"<<str.getC(6)<<endl;
cout<<"th string length is :"<<str.strLen()<<endl;
MyString str2 = str;
cout<<"str2 call copy constructor with str is: "<<str2.getS()<<endl;
MyString str3;
str3 = str;
cout<<"str3 call operator= with str is: "<<str3.getS()<<endl;
}
页:
[1]