Use C++ to write a basic String class that provides the following methods in the
ID: 3538860 • Letter: U
Question
Use C++ to write a basic String class that provides the following methods in the String class for setting up, accessing and changing strings (overloading operators (2) to (7) internally and (9) externally):
(1) Add a new constructor that initializes the String object by a string s.
String(const char s[]);
(2) String operator +=(const String &str); // formerly void append(const String &str);
Overload += operator. A method that returns a string formed by appending the passed String with the String the method is called on,
(4) bool operator ==(const String &str) const;
(5) bool operator !=(const String &str) const;
(6) bool operator >(const String &str) const;
(7) bool operator <=(const String &str) const;
// all of them are formerly int compare_to(const String &str) const; that compares the String object with the String passed to this method. Each returns a true or false value based on whether the relationship (e.g., ==, !=, >, <, >=, <=) holds or not.
(8) void print(ostream &out) const; //formerly void print() const; which only prints to standard output screen
A method that prints the value of the String it is called on to ostream object out.
Note: In your implementation of String's methods, you may use the library functions provided by , which operate on the C style string.
Explanation / Answer
#include <iostream>
#include <string.h>
#include <stdlib.h>
#include <fstream>
using namespace std;
class String
{
private:
char contents[];
public:
String(const char []);
String operator +=(const String &str);
char operator [](int i) const;
bool operator ==(const String &str) const;
bool operator !=(const String &str) const;
bool operator >(const String &str) const;
bool operator <=(const String &str) const;
void print(ostream &out) const;
~String(){};
/* data */
};
ostream & operator<<(ostream &out, const String & r);
String :: String(const char str[])
{
strcpy(contents,str);
}
String String :: operator +=(const String &str)
{
int size;
for(size=0;str[size];size++);
char temp[size+1];
for(int i=0;i<=size;i++)
temp[i] = str[i];
strcat(contents,temp);
return *this;
}
char String :: operator [](int i) const
{
return contents[i];
}
bool String::operator ==(const String &str) const
{
return strcmp(contents, str.contents) == 0;
}
bool String::operator !=(const String &str) const
{
return strcmp(contents, str.contents) != 0;
}
bool String::operator >(const String &str) const
{
return strcmp(contents, str.contents) > 0;
}
bool String::operator <=(const String &str) const
{
return strcmp(contents, str.contents) <= 0;
}
void String :: print(ostream &out) const
{
for(int i=0;contents[i];i++)
out << contents[i];
}
ostream & operator<<(ostream &out, const String & r)
{
for(int i=0;r[i];i++)
out << r[i];
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.