3 // ---------------------------------------------------------------------------
12 * Simplified string class.
13 * It provides only few basic functions of the standard <string> and
14 * is intended to be used as a replacement of the standard class where
15 * full functionality of <string> is not required, but it is essential
16 * to have highly portable and effective code.
18 * This file should be used exclusively inside *.cc files.
19 * Usage inside header files can result to a clash with standard <string>.
23 char* s; // pointer to data
24 int n; // reference count
28 // Default constructor.
29 string() { p = new srep; p->s = 0; }
31 // Constructor from character string.
32 string(const char* s) {
33 p = new srep; p->s = new char[strlen(s)+1]; strcpy(p->s, s);
36 // Constructor from character substring.
37 string(const char* s, unsigned int n) {
38 p = new srep; p->s = new char[n+1]; strncpy(p->s, s, n); *(p->s+n) = '\0';
41 // Copy constructor from string.
42 string(const string& x) { x.p->n++; p = x.p; }
45 ~string() { if (--p->n == 0) { delete [] p->s; delete p; } }
47 // Assignment from character string.
48 string& operator=(const char* s) {
49 if (p->n > 1) { // disconnect self
53 delete [] p->s; // free old string
55 p->s = new char[strlen(s)+1];
60 // Assignment from string.
61 string& operator=(const string & x) {
62 x.p->n++; // protect against "st = st"
63 if (--p->n == 0) { delete [] p->s; delete p; }
68 // Returns C-style character string.
69 const char* c_str() const { return p->s; }
75 inline string operator+(char a, const string & b) {
76 string s; s.p->s = new char[strlen(b.c_str())+2];
77 s.p->s[0] = a; strcpy(s.p->s+1, b.c_str());
81 inline string operator+(const char * a, const string & b) {
83 string s; s.p->s = new char[lena+strlen(b.c_str())+1];
84 strcpy(s.p->s, a); strcpy(s.p->s+lena, b.c_str());
88 inline string operator+(const string & a, const char * b) {
89 int lena = strlen(a.c_str());
90 string s; s.p->s = new char[lena+strlen(b)+1];
91 strcpy(s.p->s, a.c_str()); strcpy(s.p->s+lena, b);
95 inline string operator+(const string & a, const string & b) {
96 int lena = strlen(a.c_str());
97 string s; s.p->s = new char[lena+strlen(b.c_str())+1];
98 strcpy(s.p->s, a.c_str()); strcpy(s.p->s+lena, b.c_str());
105 inline bool operator==(const string & x, const char* s) {
106 return strcmp(x.p->s, s) == 0;
108 inline bool operator==(const string & x, const string & y) {
109 return strcmp(x.p->s, y.p->s) == 0;
111 inline bool operator!=(const string & x, const char* s) {
112 return strcmp(x.p->s, s) != 0;
114 inline bool operator!=(const string & x, const string & y) {
115 return strcmp(x.p->s, y.p->s) != 0;
119 // Output to a stream.
121 std::ostream & operator<<(std::ostream & s, const string & x) {
125 #endif /* HEP_STRING_SRC */