/* name: simplestring.cxx ** author: L. Liberti */ #include<iostream> #include<cstring> #include "simplestring.h" inline int max(int a, int b) { if (a >= b) { return a; } else { return b; } } SimpleString::SimpleString() : buffer(NULL), theSize(0), theAllocatedSize(0), theZeroChar('\0') { } SimpleString::SimpleString(char* initialiseFromArray) { using namespace std; theSize = strlen(initialiseFromArray); int s = max(theSize, theMinimalAllocationSize); buffer = new char [s]; theAllocatedSize = s; strcpy(buffer, initialiseFromArray); } SimpleString::~SimpleString() { if (buffer) { delete [] buffer; } } int SimpleString::size(void) const { return theSize; } char& SimpleString::operator[](int i) { if (i >= theSize || i < 0) { return theZeroChar; } else { return buffer[i]; } } void SimpleString::copyFrom(SimpleString& s) { if (buffer) { delete [] buffer; } int ss = s.size(); int ssalloc = max(ss, theMinimalAllocationSize); buffer = new char[ss]; for(int i = 0; i < ss; i++) { buffer[i] = s[i]; } theSize = ss; } void SimpleString::append(SimpleString& suffix) { int ss = suffix.size(); if (ss > theAllocatedSize - theSize) { // suffix does not fit, reallocate char* saveBuffer = buffer; int s = theSize + ss + 1; buffer = new char [s]; theAllocatedSize = s; strcpy(buffer, saveBuffer); delete [] saveBuffer; } for(int i = 0; i < ss; i++) { buffer[i + theSize] = suffix[i]; } theSize = theSize + ss; buffer[theSize] = '\0'; } bool SimpleString::contains(SimpleString& needle) const { int s = needle.size(); bool found; for(int i = 0; i < theSize - s; i++) { found = true; for(int j = i; j < s + i; j++) { if (buffer[j] != needle[j - i]) { found = false; break; } } if (found) { break; } } return found; } std::ostream& operator<<(std::ostream& out, SimpleString& s) { int ss = s.size(); for(int i = 0; i < ss; i++) { out << s[i]; } return out; }
The makefile is as follows.
all: ssmain ssmain: ssmain.cxx simplestring.o $(CXX) -o ssmain ssmain.cxx simplestring.o simplestring.o: simplestring.h simplestring.cxx $(CXX) -c simplestring.cxx clean: $(RM) -f simplestring.o ssmain