home *** CD-ROM | disk | FTP | other *** search
- #pragma +
-
- class String
- { char *str;
- int len;
- void free();
- void alloc (const char*);
- String (int, char*);
- public:
- String (const char* = 0);
- String (const String &);
- ~String();
- operator char*() const
- { if (str) return str;
- else return "";
- }
- String &operator = (const String &);
- char operator[] (int i) const;
- int length() const
- { return len; }
- friend String operator + (const String &s1, const String &s2);
- };
-
-
- int operator == (const String &s1, const String &s2);
-
- class ostream& operator << (ostream&, const String&);
-
- #include <string.h>
- #include <stream.h>
-
- void String::alloc (const char *initstr)
- { if (initstr)
- { len = strlen(initstr);
- str = new char[len+1];
- if (str)
- strcpy(str, initstr);
- else
- len = 0;
- }
- else
- { len = 0;
- str = 0;
- }
- }
-
- void String::free()
- { if (str)
- { delete [] str;
- str = 0;
- }
- }
-
- String::String (int len, char *str) : len(len), str(str) { }
-
- String::String (const char *initstr)
- { alloc(initstr); }
-
- String::String (const String &s)
- { alloc (s.str); }
-
- String::~String()
- { free(); }
-
- String operator + (const String &s1, const String &s2)
- {
- int newlen = s1.length()+s2.length();
- char *newstr = new char[newlen+1];
- if (newstr)
- { strncpy (newstr,s1,s1.length());
- strncat (newstr,s2,s2.length())
- }
- return String(newlen, newstr);
- }
-
- String &String::operator = (const String &s)
- { free();
- alloc(s.str);
- return *this;
- }
-
- char String::operator[] (int index) const
- { if(str && unsigned(index) <= unsigned(len) )
- return str[index];
- else
- return '\0';
- }
-
- int operator == (const String &s1, const String &s2)
- { return !strcmp(s1,s2); }
-
- ostream &operator << (ostream& out, const String& s)
- { return out << (char*)s; }
-
- // Testroutine:
-
- void main()
- {
- String s1, s2="I didn't expect the", s3;
- s1 = "Spanish Inquisition";
- s3 = s2 + " " + s1;
-
- char *awurx = "Vor"+"sicht"; // unsichere Operation!
-
- int i = "Test"=="Test", // implementationsabhängig
- j = String("Test")==String("Test"); // true
-
- cout << s3+".\n";
- }
-