#include <string.h>
#include "CString2.h"

CString2::CString2()
    : len(0), str(NULL)
{
    cout << "constructeur par defaut  : CString2()" << endl;
}

CString2::CString2(const char * s)
    :  len(strlen(s)), str(NULL)
{
    cout << "constructeur  : CString2(const char * s)" << endl;
    str = new char [len + 1];
    strcpy(str, s);
}

CString2::CString2(const CString2 & s)
    : len(s.len), str(NULL)
{
    cout << "constructeur de copie : String(const CString2 & s)" << endl;
    str = new char [len + 1];
    strcpy(str, s.str);
}

// destructeur
CString2::~CString2()
{
    cout << "destructeur : ~CString2()" << endl;
    if (str != NULL)
        delete str;
}

size_t CString2::length ( )
{
    return len;
}

const char * CString2::getStr() const
{
    return str;
}

void CString2::setStr(const char * s)
{
    if (strlen(str) < strlen(s))
    {
        if (str != NULL)
            delete str;
        len = strlen(s);
        str = new char [len + 1];
    }
    strcpy(str, s);
}

CString2 & CString2::operator= (const CString2 & s)
{
    cout << "assignment operator : String & operator= (const CString2 & s)" << endl;

    if (this == &s)
        return *this;

    if (s.str == NULL)
    {
        str = NULL;
        len = 0;
        return *this;
    }

    if (str != NULL)
        delete str;
    len = s.len;
    str = new char [len + 1];
    strcpy(str, s.str);
    return *this;
}

CString2 CString2::operator+(const CString2 & s) const
{
    cout << "operator+ : String operator+ (const CString2 & s)" << endl;
    CString2 res;
    res.len = len + s.len;
    res.str = new char [res.len + 1];
    strcpy(res.str, str);
    strcat(res.str, s.str);
    return res;
}

bool CString2::operator>(const CString2 & s) const
{
    if (strcmp(str, s.str) > 0)
        return true;
    return false;
}

bool CString2::operator<=(const CString2 & s) const
{
     if (strcmp(str, s.str) <= 0)
        return true;
    return false;
}

ostream & operator<<(ostream & os, const CString2 & s)
{
    if (s.str != NULL)
        os << s.str;
    return os;
}
