| | | | | next -> |

String Implementation: Helper Methods

  void String::Clone(const String& s)
  // Dangerous -- take care not to apply to *this !
  {
    size_ = s.Size();
    if (s.data_)
      {
        data_ = NewCstr(size_);
        StrCpy (data_, s.data_);
      }
    else
      {
        data_ = 0;
      }
  } // end Clone()

  char* String::NewCstr(int n)
  // creates a new C-string of size n (array size = n+1)
  // with memory allocation error message
  {
    char* Cptr;
    if (n >= 0)
      {
        Cptr = new char [n + 1];
        if (Cptr == 0)
          {
            Error("memory allocation failure");
          }
        Cptr[n] = '\0';
      }
    else
      Cptr = 0;
    return Cptr;
  } // end NewCstr()

  int String::StrLen(const char* s)
  // a version of strlen()
  {
    int len = 0;
    if (s != 0)
      {
        for (len = 0; s[len] != '\0'; ++len){}
      }
    return len;
  } // end StrLen()

  void String::StrCpy(char* s1, const char* s2)
  // a version of strcpy(); DOES NOT CHECK OPERAND ARRAY SIZES
  {
    if (s2 != 0)
      {
        if (s1 != 0)
          {
            int i;
            for (i = 0; s2[i] != '\0'; ++i)
              s1[i] = s2[i];
            s1[i] = '\0';
          }
        else
          {
            Error("StrCpy() operand 0");
          }
      }
  } // end StrCpy()

  void String::Error(const char* msg)
  {
    std::cerr << "** String error: " << msg << '\n';
    exit (EXIT_FAILURE);
  }

| next -> | Top of Page | 3. C Strings, Proper Type, and String Objects - 17 of 17