Create a class string whose private data member is a character array of size 50. Create the constructor in default constructor assigns the null into the string. In parameter, constructor assigns the string which is passed by the user. Overload the '+'operator to add two string values. Overload the =' to compare to strings. Create its disp( function to display the string.
#include <iostream>
using namespace std;
//a class string whose private data member is a character array of size 50.
class String
{
private:
char characters[50];
public:
//the constructor in default constructor assigns the null into the string.
String(){
for(int i=0;i<50;i++){
characters[i]=NULL;
}
}
//In parameter, constructor assigns the string which is passed by the user.
String(char userCharacters[]){
for(int i=0;i<50;i++){
this->characters[i]=userCharacters[i];
}
}
//function to display the string.
void display(){
for(int i=0;i<50;i++){
if(characters[i]!=NULL){
cout<<this->characters[i];
}
}
}
//Overload the '+'operator to add two string values.
String operator+(String otherString)
{
String newString;
strcat(this->characters, otherString.characters);
strcpy(newString.characters,this->characters);
return newString;
}
//Overload the '==' to compare to strings.
bool operator==(String otherString)
{
for(int i=0;i<50;i++){
if(characters[i]!=otherString.characters[i]){
return false;
}
}
return true;
}
};
int main()
{
char characters1[50]="First string";
char characters2[50]="Second string";
String string1(characters1);
string1.display();
cout<<"\n";
String string2(characters2);
string2.display();
cout<<"\n";
cout<<"\nAdd two string values:\n";
String stringAdd=string1+string2;
stringAdd.display();
cout<<"\n\nCompare two strings:\n";
if(string1==string2){
cout<<"string1 == string2\n\n";
}else{
cout<<"string1 <> string2\n\n";
}
system("pause");
return 0;
}
Comments
Leave a comment