Wednesday, July 28, 2010

STRING OVERLOADING

#include<stdio.h>
#include<iostream>
using namespace std;
class str
{
 char *p;
 int len;
 public:
        str()
        {
        len=0;
        p=0;
        }
        str(const char *s);
        str(const str &s);
        friend str operator+(const str &s,const str &t);
        friend int operator>(const str &s,const str &t);
        friend int operator==(const str &s,const str &t);
        friend void show(const str &s);
};
str::str(const char *s)
{
 len=strlen(s);
 p=new char[len+1];
 strcpy(p,s);
}
str::str(const str &s)
{
 len=s.len;
 p=new char[len+1];
 strcpy(p,s.p);
}
int operator>(const str&s,const str &t)
{
 int m=strlen(s.p);
 int n=strlen(t.p);
 if(m>n)
 return(1);
 else if(m==n)
 {
 show(s.p);
 cout<< " equals to ";
 show(t.p);
 cout<<endl;
 }
 else
 {
 show(s.p);
 cout<< " lesser than ";
 show(t.p);
 cout<<endl;
 }
}
void show(const str &s)
{
 cout<<s.p;
}
str operator+(const str &s,const str &t)
{
 str temp;
 temp.len=s.len+t.len;
 temp.p=new char[temp.len+1];
 strcpy(temp.p,s.p);
 strcat(temp.p,t.p);
return(temp);
}
int main()
{
str t1,t2,t3;
int ch;
char s1[100],s2[100];
cout<<"enter two strings s1 and s2\n";
cin>>s1>>s2;
t1=s1;
t2=s2;
cout<<"given strings are\n";
cout<<"string1==";
show(t1);
cout<<endl;
cout<<"string2=";
show(t2);
cout<<endl;
while(1)
{
cout<<"STRING FUNCTIONS\n";
cout<<"1.comparision\n2.concatenation\n3.exit\nenter your choice:\t";
cin>>ch;
switch(ch)
{
case 1:if(t1>t2)
       {
       show(t1);
       cout<<" is greater than ";
       show(t2);
       cout<<endl;
       }
       break;
case 2:t3=t1+t2;
       cout<<"concatenated string is ";
       show(t3);
       cout<<endl;
       break;
case 3:exit(1);
        break;
}
}
return(0);
}



No comments:

Post a Comment

FOLLOWERS