String Class
#include < stdio.h >
#include < stdlib.h >
#include < iostream.h >
#include < string.h >
class String
{
public:
String();
String(const char *s);
String(char c, int n);
void set(int index, char newchar);
char get(int index) const;
int getLength() const { return length; }
void append(const char *addition);
void operator=(const String *other);
void display();
~String();
private:
int length;
char *buf;
};
String::String()
{
buf = 0;
length = 0;
}
String::String(const char *s)
{
length = strlen(s);
buf = new char[length+1];
strcpy(buf, s);
}
String::String(char c, int n)
{
length = n;
buf = new char[length+1];
memset(buf, c, length);
buf[length] = '\0';
}
void String::set(int index, char newchar)
{
if (index > 0 && index <= length) buf[index-1] = newchar;
}
char String::get(int index) const
{
if (index > 0 && index <= length) return buf[index-1];
else return 0;
}
void String::append(const char *addition)
{
char *temp;
length += strlen(addition);
temp = new char[length+1];
sprintf(temp, "%s%s", buf, addition);
delete(buf);
buf = temp;
}
void String::operator=(const String *other)
{
length=other->length;
delete(buf);
buf=new char[length+1];
strcpy(buf, other->buf);
}
void String::display()
{
cout << "The string: " << buf << '\n';
}
String::~String()
{
delete(buf);
}
main()
{
String mystring("This is a string");
String ostring("");
mystring.set(1,'t');
mystring.display();
mystring.append(". And now an appendage.");
mystring.display();
ostring = mystring;
ostring.display();
}