Sei sulla pagina 1di 3

CS125: Programming Fundamentals

Lab No. 10 String Class

Objective
1. 2. 3. 4. 5. 6. 7. 8. 9. String Class Constructor Overloading Dynamic Memory Allocation User Defined append Function User Defined Length function Copy String Function Destructor. Operator overloading Copy Constructor

String Class
class MyString { char *p; int dlength; int capacity; };

Default constructor
MyString() { setlength(0); p = new char[capacity]; p[dlength]= '\0'; }

Constructor Overloading
MyString( char * cstr) { setlength(len(cstr)); p = new char[capacity]; copy(cstr); // copy function defined below p[dlength]= '\0'; }

Lab No. 11: String Class

CS125: Programming Fundamentals

Copy Function
void copy(char * cstr) { for(int i=0; i<dlength; i++) p[i] = cstr[i]; }

Length Function
int len(char * cstr) { int len=0; while(cstr[len]) { len++; } return len; }

Copy and length function are private. No one can access these functions directly.

Length Public Function


void setlength(int l) { dlength=l; capacity=dlength+1; } int length() { return dlength; }

These are public function for getting and setting of length in class.

Operator Overloading [ ]
char & operator [](int i) { return p[i]; }

Operator Overloading +=
void operator +=(MyString& s) { char *ms; capacity=dlength+s.length() +1;; ms=new char[capacity]; int index=0; for(int j=0; j<dlength; j++) { ms[j]=p[j]; index++;

Lab No. 11: String Class

CS125: Programming Fundamentals


} dlength=dlength+s.length(); for(int k=0; k<s.length(); k++) { ms[index]=s[k]; index++; } ms[dlength] = '\0'; delete [] p; p=ms; }

This operator overloading will perform like append text in a string.

Exercise 1
Write a function in class which concatenate two strings. Return a string object.

Destructor
~MyString() { delete [] p; }

Is it necessary to use Destructor. If yes then Why?

Main Function
int main() { MyString s; MyString ss="hello"; MyString ss4="World"; //int n=ss.Len(); //cout<<ss.at(4); //cout<<ss[3]; ss[4]='5'; ss+=ss4; //system("pause"); return 0; }

Exercise 2
Write a function which compares two strings. Write a function which replace a set of characters in string from given index number.

Checked By:

Date: August 28 , 2013

Lab No. 11: String Class

Potrebbero piacerti anche