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

} These are public function for getting and setting of length in class. ms=new char[capacity]. j++) { ms[j]=p[j]. i<dlength. 11: String Class . j<dlength. } return len. Length Public Function void setlength(int l) { dlength=l.. } Length Function int len(char * cstr) { int len=0. Lab No. } Copy and length function are private.length() +1. int index=0. } Operator Overloading += void operator +=(MyString& s) { char *ms.CS125: Programming Fundamentals Copy Function void copy(char * cstr) { for(int i=0. } int length() { return dlength. for(int j=0. i++) p[i] = cstr[i]. capacity=dlength+1. while(cstr[len]) { len++. No one can access these functions directly. index++. Operator Overloading [ ] char & operator [](int i) { return p[i]. capacity=dlength+s.

} Exercise 2   Write a function which compares two strings. 2013 Lab No. } ms[dlength] = '\0'. for(int k=0. Return a string object. Write a function which replace a set of characters in string from given index number. k<s. If yes then Why? Main Function int main() { MyString s. p=ms. ss[4]='5'.Len(). Exercise 1 Write a function in class which concatenate two strings. ss+=ss4. //cout<<ss[3]. } Is it necessary to use Destructor.at(4). delete [] p. } This operator overloading will perform like append text in a string. 11: String Class .length(). Destructor ~MyString() { delete [] p. MyString ss="hello". index++. //int n=ss. return 0. Checked By: Date: August 28 . //system("pause").length(). //cout<<ss. k++) { ms[index]=s[k]. MyString ss4="World".CS125: Programming Fundamentals } dlength=dlength+s.

Sign up to vote on this title
UsefulNot useful

Master Your Semester with Scribd & The New York Times

Special offer for students: Only $4.99/month.

Master Your Semester with a Special Offer from Scribd & The New York Times

Cancel anytime.