Vec.h
see note 11
Str.h
#ifndef GUARD_Str_h
#define GUARD_Str_h
// Str.h
#include <cstring> //strlen()
#include <algorithm>
#include <iostream>
#include "Vec.h"
class Str {
friend std::istream& operator>>(std::istream&, Str&);
public:
typedef Vec<char>::size_type size_type;
// default constructor; creat an empty Str
Str(): p_c_str(NULL), p_data(NULL) { }
// create a Str containing n copies of c
Str(size_type n, char c): chars(n, c), p_c_str(NULL), p_data(NULL) { }
// create a Str from a null-terminated array of char
Str(const char* cp): p_c_str(NULL), p_data(NULL) {
std::copy(cp, cp + std::strlen(cp), std::back_inserter(chars));
}
~Str() {
if (p_c_str)
delete[] p_c_str;
if (p_data)
delete[] p_data;
}
// create a Str from the range denoted by iterators b and e
template <class In> Str(In b, In e): p_c_str(NULL), p_data(NULL) {
std::copy(b, e, std::back_inserter(chars));
}
char& operator[] (size_type i) { return chars[i]; }
const char& operator[] (size_type i) const { return chars[i]; }
size_type size() const { return chars.size(); }
Str& operator+=(const Str& s) {
std::copy(s.chars.begin(), s.chars.end(), std::back_inserter(chars));
return *this;
}
char* c_str();
char* data();
private:
Vec<char> chars;
char* p_c_str;
char* p_data;
};
std::ostream& operator<<(std::ostream&, const Str&);
Str operator+(const Str&, const Str&);
#endif
Str.cpp
// source file Str-related
#include <cctype>
#include "Str.h"
using std::istream; using std::ostream;
istream& operator>>(istream& in, Str& s) {
// obliterate existing value(s)
s.chars.clear();
char c;
while(in.get(c) && isspace(c))
;
if (in) {
do s.chars.push_back(c);
while (in.get(c) && !isspace(c));
if (in)
in.unget();
}
return in;
}
ostream& operator<<(ostream& out, const Str& s) {
for (Str::size_type i = 0; i != s.size(); ++i)
out << s[i];
return out;
}
Str operator+(const Str& s, const Str& t) {
Str r = s;
return r += t;
}
char* Str::c_str() {
if (p_c_str)
delete[] p_c_str;
p_c_str = new char[chars.size() + 1];
for (size_type i = 0; i != chars.size(); ++i)
p_c_str[i] = chars[i];
p_c_str[chars.size()] = '\0';
return p_c_str;
}
char* Str::data() {
if (p_data)
delete[] p_data;
p_data = new char[chars.size()];
for (size_type i = 0; i != chars.size(); ++i)
p_data[i] = chars[i];
return p_data;
}
main.cpp
#include <iostream>
#include <string>
#include "Str.h"
using std::cout; using std::endl; using std::string;
int main() {
Str s;
Str k = "kang";
Str r("rui");
Str h = "huan";
string str = "lzj";
Str l(str.begin(), str.end());
s = k + r + h;
cout << s << endl;
cout << s.size() << endl;
cout << l << endl;
char* cp = l.c_str();
char* cp2 = l.data();
char ch = *cp;
cout << ch << endl;
cout << cp << endl;
cout << sizeof(cp) << endl;
cout << cp2 << endl;
cout << sizeof(cp2) << endl;
cout << cp[1] << endl;
}