Your own string class : Your string « Data Types « C++ Tutorial






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

class String
{
  char *p;
  int length;
public:
  String();
  String(char *str,int len);
  char *getstring(){return p;}
  int getlength(){return length;}
};
String::String()
{
  p=new char[255];
  if(!p)
  {
    cout<<"Allocation erroe\n";
       exit(1);
  }
  *p='\0';
  length=255;
}
String::String(char * str,int len)
{
  if(strlen(str)>=len)
  {
    cout<<"Allcation too little memory! \n";
       exit(1);
  }
  p=new char[len];
  if(!p)
  {
    cout<<"Allocation error\n";
       exit(1);
  }
  strcpy(p,str);
  length=len;
}
main()
{
  String ob1;
  String ob2("This is a string.",100);
  cout<<"ob1:"<<ob1.getstring()<<"-Allocation length:";
  cout<<ob1.getlength()<<'\n';
  cout<<"ob2:"<<ob2.getstring()<<"-Allocation length:";
  cout<<ob2.getlength()<<'\n';
  return 0;
}
ob1:-Allocation length:255
ob2:This is a string.-Allocation length:100








2.42.Your string
2.42.1.Your own string class
2.42.2.Define and use a string class
2.42.3.convert between ordinary strings and class String
2.42.4.strings defined using array and pointer notation