WELCOME

Welcome to KoDes4U

Pages

Tuesday, March 8, 2011

operator overlaoding for string (C++ program)

/*Write a C++ program to perform String operations
1. = Equality
2. == String compare
3. +Concatenation
4. << To display a string
5. >> To reverse a string
6. Function to determine whether a string is pallindrome......................................coded for KoDes4U.blogspot.com*/

#include
#include
#include
class string
{
public:
char str1[20],str2[20];
void operator +(string s) //concatenation
{
strcat(s.str1,s.str2);
cout<<"\nConncatenated string is:"< }
int operator=(string s)
{
int i;
i=strcmp(s.str1,s.str2);
if(i==0)
cout<<"\nBoth are same:";
else if(i>0)
cout<<"\n1st string is greater";
else
cout<<"\n2nd string is greater";
return 0;
}
void operator==(string s)
{
strcpy(s.str1,s.str2);
cout<<"\noriginal string is:"< cout<<"\ncopied string is :"< }
void operator <<(string s)
{
cout<<"1st string is:"< cout<<"\n2nd Strring is:"< }
void operator >>(string s)
{
cout<<"Original string is:"< strrev(s.str1);
cout<<"\nReversed string is:"< cout<<"\nOriginal string is:"< strrev(s.str2);
cout<<"\nReversed string is:"< }
void pallindrome(string s);
};
void string::pallindrome(string s)
{
char c[20],d[20];
int result;
cout<<"First string is ";
strcpy(c,s.str1);
strrev(c);
result=strcmp(s.str1,c);
if(result==0)
cout<<"Pallindrome";
else
cout<<"not a pallindrome";
cout<<"\nSecond string is ";
strcpy(d,s.str2);
strrev(d);
result=strcmp(s.str2,d);
if(result==0)
cout<<"Pallindrome:";
else
cout<<"Not a paliindrome";
}
void main()
{
string s;
int op;
clrscr();
cout<<"Enter the two strings:";
cin>>s.str1>>s.str2;
do
{
cout<<"\n1)Concat\n2)compare\n3)copy\n4)reverse\n5)pallindrome\n6)Exit";
cout<<"\nEnter your choice:";
cin>>op;
switch(op)
{
case 1:s+(s);break;
case 2:s=(s);
break;
case 3:s==(s);break;
case 4:s>>(s);break;
case 5:s.pallindrome(s);break;
default:cout<<"Press any key to exit:";break;
}
}
while(op!=6);
getch();
}

No comments:

Post a Comment