Index

C & C++ Programming - String Operations

#include "string.h"

class CMyString
{
private:
 char a[200];

public:
 CMyString(char *s='\0') {strcpy(a,s);}
 void read() {cout<<"\n Enter a string\n";cin>>a;}
 CMyString operator +(CMyString x);
 CMyString operator +(char *x);
 CMyString operator +(char x);
 friend CMyString operator +(char *x,CMyString y);
 CMyString operator=(CMyString x);
 int operator==(CMyString x);
 int operator>(CMyString x);
 int operator>=(CMyString x);
 int operator<(CMyString x);
 int operator<=(CMyString x);
 int find(char *x);
 CMyString left(int x);
 CMyString right(int x);
 CMyString mid(int x,int y);
 void display() {cout << a; }
};

CMyString CMyString:: operator +(CMyString x)
{
 CMyString t;
 strcpy(t.a,a);
 strcat(t.a,x.a);
 return t;
}

CMyString CMyString:: operator +(char x)
{
 CMyString t;
 strcpy(t.a,a);
 int l=strlen(t.a);
 t.a[l]=x;
 t.a[l+1]='\0';
 return t;
}

CMyString CMyString:: operator +(char *x)
{
 CMyString t;
 strcpy(t.a,a);
 strcat(t.a,x);
 return t;
}

CMyString operator +(char *x,CMyString y)
{
 CMyString t;
 strcpy(t.a,x);
 strcat(t.a,y.a);
 return t;
}

int CMyString:: operator==(CMyString x)
{
 if(strcmp(a,x.a)==0)
  return 1;
 else
  return 0;
}

int CMyString:: operator>(CMyString x)
{
 if(strcmp(a,x.a)>0)
  return 1;
 else
  return 0;
}
int CMyString:: operator<(CMyString x)
{
 if(strcmp(a,x.a)<0)
  return 1;
 else
  return 0;
}
int CMyString:: operator>=(CMyString x)
{
 if(strcmp(a,x.a)>=0)
  return 1;
 else
  return 0;
}

CMyString CMyString:: operator=(CMyString x)
{
 strcpy(a,x.a);
 return a;
}

int CMyString:: operator<=(CMyString x)
{
 if(strcmp(a,x.a)<=0)
  return 1;
 else
  return 0;
}
CMyString CMyString::left(int x)
{
 CMyString s;
 for(int i = 0; i < x; i++) {
  s.a[i] = a[i];
 }
 s.a[i] = '\0';
 return s;
}

CMyString CMyString::right(int x)
{
 CMyString s;
 int y=strlen(a);
 int p=0;
 for(int i = 0;i < y; i++)
 {
  if(i>=(y-x))
  {
   s.a[p]=a[i];
   p++;
  }
 }
 s.a[p]='\0';
 return s;
}

CMyString CMyString::mid(int x,int y)
{
 CMyString s;
 int p=0;
 x--;
 for(int i = x;i < x+y; i++)
 {
  s.a[p]=a[i];
  p++;
 }
 s.a[p]='\0';
 return s;
}

int CMyString:: find(char *x)
{
 char *p;
 int ct=0;
 p=strstr(a,x);
 while(p!=NULL)
 {
  p=strstr(p,x);
  if(p!=NULL)
  {
   ct++;
   p++;
  }
 }
 return ct;
}

int TestString()
{
 CMyString a1("infodmbsvfodm "), a2("way"), a3;
 int x=a1.find("odmb");
 cout << x;
 return 0;
}
Index