Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
C++ program to implement a string class and make use of operator overloading:
#include<iostream>
#include<cstring>
using namespace std;
class sstring{
char* s;
int len;
public:
sstring();
sstring operator +(sstring a);
sstring operator -(sstring a);
bool operator ==(sstring a);
bool operator >(sstring a);
bool operator <(sstring a);
friend istream& operator >>(istream &inp,sstring &a){
char x[100];
inp>>x;
a.len=strlen(x);
a.s=new char[a.len+1];
strcpy(a.s,x);
return inp;
}
friend ostream& operator <<(ostream &out,sstring &a){
out<<a.s<<endl;
return out;
}
};
sstring::sstring(){
len=0;
s=new char[len+1];
}
sstring sstring::operator+(sstring a){
sstring t;
t.len=len+a.len;
t.s=new char[t.len+1];
strcpy(t.s,s);
strcat(t.s," ");
strcat(t.s,a.s);
return t;
}
sstring sstring::operator-(sstring a){
sstring t;
int x,y,i,j,k;
int flag,ok=0;
for(i=0;i<len-a.len;i++){
flag=0;
k=0;
for(j=i;j<i+a.len;j++){
if(s[j]!=a.s[k++]){
flag=1;
}
}
if(flag==0){
x=i;
y=i+a.len-1;
ok=1;
break;
}
}
if(ok==0){
cout<<"Substring not found\n";
return *this;
}
t.len=len-a.len;
t.s=new char[t.len+1];
j=0;
for(i=0;i<len;i++){
if(i<x || i>y){
t.s[j++]=s[i];
}
}
t.s[j]='\0';
return t;
}
bool sstring::operator ==(sstring a){
if(strcmp(s,a.s)==0)return true;
else return false;
}
bool sstring::operator<(sstring a){
if(strcmp(s,a.s)<0)return true;
else return false;
}
bool sstring::operator>(sstring a){
if(strcmp(s,a.s)>0)return true;
else return false;
}
int main()
{
int ch;
cout<<"Choice: 1) Concatenation 2) String Deletion 3) String Compare 3) Exit";
sstring a,b,c;
while(1){
cout<<"\nEnter your choice..";
cin>>ch;
if(ch==1){
cout<<"Enter the first string ";
cin>>a;
cout<<"Enter the second string ";
cin>>b;
c=a+b;
cout<<"\nThe concatenation of the given two strings is "<<c;
}
else if(ch==2){
cout<<"Enter the string ";
cin>>a;
cout<<"Enter the substring to be deleted ";
cin>>b;
c=a-b;
cout<<"\nThe resultant string is "<<c;
}
else if(ch==3){
cout<<"Enter the first string ";
cin>>a;
cout<<"Enter the second string ";
cin>>b;
if(a==b){
cout<<"The given two strings are equal.";
}
else if(a>b){
cout<<"The first string is greater than the second string.";
}
else if(a<b){
cout<<"The first string is lesser than the second string.";
}
}
else{
break;
}
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.