Senin, 07 April 2014

A Multi Purpose String Class in C

NOTE: Here I present you with a String Class in C++. We have
pre-defined string class (CString in Microsoft Visual C++) which has similar but
more powerful to the one presented here but using something is one thing and learning
how it works is another. Here I show you how string functions actually work. All
the functions are programmed from the scratch without using any other standard
library function. Look at the program (Class) carefully and try to understand
how each of the function is working.

  //-----------------------------
//-----------myClass-----------
//----A String Class in C++----

#include<iostream.h>
#include<stdlib.h>

class myString
{
private:

// these functions are not
// needed outside the class
void allocate(int);
void copy(char *, char *);

public:

   char *string;

// member functions
myString();
myString(char *);
int getLength();
int getLength(char *);
void empty();
bool isEmpty();
void putString(char *);
char *getString();
char *fromLeft(int);
char *fromRight(int);
char *fromMid(int, int);
~myString();
};

//--------------------------------
//------------MEMBER--------------
//---FUNCTION DEFINITION STARTS---
void myString::allocate(int size)
{
empty();

string=new char[size];
if(string==NULL) exit(0);
}

void myString::copy(char *str1, char *str2)
{
int length=getLength(str2);

for(int i=0;i<=length;i++)
str1[i]=str2[i];
}

void myString::empty()
{
if(string!=NULL)
{
delete []string;
string=NULL;
}
}

bool myString::isEmpty()
{
if(string!=NULL)
return false;

return true;
}

int myString::getLength(char *str)
{
int i=0;

while(str[i]!=

Related Posts by Categories

0 komentar:

Posting Komentar