home *** CD-ROM | disk | FTP | other *** search
- // -------- strings.cpp
-
- #include <iostream.h>
- #include <string.h>
- #include "strings.h"
-
- // ------- put a string into a String
- void String::putstr(char *s)
- {
- if (s == NULL)
- sptr = NULL;
- else {
- sptr = new char[strlen(s)+1];
- strcpy(sptr, s);
- }
- }
-
- // ------- construct with a char * initializer
- String::String(char *s)
- {
- putstr(s);
- }
-
- // ------- construct with another String as initializer
- String::String(String& s)
- {
- putstr(s.sptr);
- }
-
- // -------- construct with just a size
- String::String(int len)
- {
- sptr = new char[len+1];
- memset(sptr, 0, len+1);
- }
-
- // -------- assign a char array to a string
- String& String::operator=(char *s)
- {
- if (sptr != NULL)
- delete sptr;
- putstr(s);
- return *this;
- }
-
- // ------- 1st concatenation operator (str1 += char *;)
- String& String::operator+=(char *s)
- {
- char *sp =
- new char[(sptr ? strlen(sptr) : 0)+strlen(s)+1];
- if (sptr != NULL) {
- strcpy(sp, sptr);
- delete sptr;
- }
- else
- *sp = '\0';
- strcat(sp, s);
- sptr = sp;
- return *this;
- }
-
- // ------ 3rd concatenation operator (str1 = str2 + char*;)
- String String::operator+(char *s)
- {
- String tmp(*this);
- tmp += s;
- return tmp;
- }
-
- // ------ 5th concatenation operator (str1 = char* + str2;)
- String operator+(char *s, String& s1)
- {
- String tmp(s);
- tmp += s1;
- return tmp;
- }
-
- // ------ substring: right len chars
- String String::right(int len)
- {
- String tmp(sptr + strlen(sptr) - len);
- return tmp;
- }
-
- // ------ substring: left len chars
- String String::left(int len)
- {
- String tmp(len+1);
- strncpy(tmp.sptr, sptr, len);
- return tmp;
- }
-
- // ------ substring: middle len chars starting from where
- String String::mid(int len, int where)
- {
- String tmp(len+1);
- strncpy(tmp.sptr,sptr+where-1,len);
- return tmp;
- }
-
- ostream& operator<<(ostream& os, String& st)
- {
- if (st.sptr != NULL)
- os << st.sptr;
- return os;
- }
-
- istream& operator>>(istream& is, String& st)
- {
- if (st.sptr != NULL)
- is >> st.sptr;
- return is;
- }