#include <cstring>
#include "string.h"
namespace ctm {
int string::num_strings = 0; //initialize static class member
int string::HowMany() { //static method
return num_strings;
}
//class methods
string::string(const char *s) { //construt string from c-string
len = std::strlen(s); //set size
str = new char [len + 1]; //allocate proper memory size
std::strcpy(str, s); //initialize pointer
num_strings++;
}
string::string() {
len = 4;
str = new char [4];
str[0] = '\0';
num_strings++;
}
string::string(const string &st) {
num_strings++;
len = st.len; //same length
str = new char [len + 1];
std::strcpy(str, st.str); //copy string to new location
}
string::~string() {
--num_strings;
delete [] str;
}
//overloaded operators
//assign a string to a string
string &string::operator=(const string &st) { //assignment
if (this == &st)
return *this;
delete [] str;
len = st.len;
str = new char [len + 1];
std::strcpy(str, st.str);
return *this;
}
//assign a c-string to a string
string &string::operator=(const char *s) {
delete [] str;
len = std::strlen(s);
str = new char [len + 1];
std::strcpy(str, s);
return *this;
}
//read-write char access for NON-CONST string
char &string::operator[](int i) {
return str[i];
}
//read-only acess access for cons string
const char &string::operator[](int i) const {
return str[i];
}
//overloaded friends
bool operator<(const string &st, const string &st2) {
return (std::strcmp(st.str, st2.str) < 0);
}
bool operator>(const string &st, const string &st2) {
return (st2.str < st.str);
}
bool operator==(const string &st, const string &st2) {
return (std::strcmp(st.str, st2.str) == 0);
}
//output and input
std::ostream &operator<<(std::ostream &os, const string &st) {
os << st.str;
return os;
}
/*std::istream &operator>>(std::istream &is, const string &st) {
char temp[string::CINLIM];
is.get(temp, string::CINLIM);
if (is) {
st = temp;
}
while (is && is.get() != '\n') {
continue;
}
return is;
}*/
}