- #1
pazmush
- 32
- 0
hi, this is what I've got so far and what I'm wanting to do is add a char to the end(and eventually the beginning) of the string but i can't seem to get it to work, do you think I've got the right idea
thanks
Code:
#include "string.h"
#include <iostream>
using namespace std;
using namespace PC3762;
string::string(char* instring)
{
_N=strlen(instring);
if (_N > 0)
{
_a = new char [_N+1];
for (size_t i = 0; i < _N; ++i )
_a[i] = instring[i];
_a[_N] = 0;
}
}string::string (const string& rca)
{
_a = NULL;
_N = rca._N;
if (_N > 0)
{
_a = new char [_N+1];
for (size_t i = 0; i < _N; ++i )
_a[i] = rca._a[i];
_a[_N]=0;
}
}
string string::operator= (const string& rhs)
{
if (&rhs == this) return *this; // Always check this for assignment.
_N = rhs._N;
delete _a; // Delete any existing array - OK even if _a == 0.
if (_N > 0)
{
_a = new char [_N+1];
for (size_t i = 0; i < _N; ++i )
_a[i] = rhs._a[i];
_a[_N]=0;
}
return (*this);
}
std::ostream& PC3762::operator<< (std::ostream& os, const string& rca)
{
os << "tring" << rca._N << ":";
for (size_t i = 0; i < rca._N; ++i )
os << ' ' << rca._a[i];
return os;
}string::~string()
{
delete _a; // OK even if _a == 0.
}
string string::operator+ (string rhs)
{
string temp("hi");
delete temp._a;
temp._a = _a;
int l=_N;
_N = _N+rhs._N;
if (_N > 0)
{
_a = new char [_N+1];
for (size_t i = 0; i < l; ++i )
_a[i] = temp._a[i];
for (size_t i = 0; i < rhs._N; ++i)
_a[l+i] = rhs._a[i];
}
return *this;
}
string string::operator+ (char rhs)
{
string temp("hi");
delete temp._a;
temp._a = _a;
int l = _N;
if (_N > 0)
{
_a = new char [_N+1];
for (size_t i = 0; i < l; ++i )
_a[i] = temp._a[i];
_a[_N+1] = rhs;
}
return *this;
}
thanks
Last edited: