home *** CD-ROM | disk | FTP | other *** search
/ Programming Languages Suite / ProgLangD.iso / C++-7 / DISK4 / SAMPLES / CPPTUTOR / STRNG.CP$ / STRNG
Encoding:
Text File  |  1991-11-08  |  1.8 KB  |  83 lines

  1. // STRNG.CPP
  2.  
  3. #include "strng.h"
  4. #include <string.h>
  5.  
  6. // Default constructor
  7. String::String()
  8. {
  9.     buf = 0;
  10.     length = 0;
  11. }
  12.  
  13. // ---------- Constructor that takes a const char *
  14. String::String( const char *s )
  15. {
  16.     length = strlen( s );
  17.     buf = new char[length + 1];
  18.     strcpy( buf, s );
  19. }
  20.  
  21. // ---------- Constructor that takes a char and an int
  22. String::String( char c, int n )
  23. {
  24.     length = n;
  25.     buf = new char[length + 1];
  26.     memset( buf, c, length );
  27.     buf[length] = '\0';
  28. }
  29.  
  30. // ----------- Copy constructor
  31. String::String( const String &other )
  32. {
  33.     length = other.length;
  34.     buf = new char[length + 1];
  35.     strcpy( buf, other.buf );
  36. }
  37.  
  38. String &String::operator=( const String &other )
  39. {
  40.     if( &other == this )
  41.         return *this;
  42.     delete buf;
  43.     length = other.length;
  44.     buf = new char[length + 1];
  45.     strcpy( buf, other.buf );
  46.     return *this;
  47. }
  48.  
  49. // ---------- Set a character in a String
  50. void String::set( int index, char newchar )
  51. {
  52.     if( (index > 0) && (index <= length) )
  53.         buf[index - 1] = newchar;
  54. }
  55.  
  56. // ---------- Get a character in a String
  57. char String::get( int index ) const
  58. {
  59.     if( (index > 0) && (index <= length) )
  60.         return buf[index - 1];
  61.     else
  62.         return 0;
  63. }
  64.  
  65. void String::append( const char *addition )
  66. {
  67.     char *temp;
  68.  
  69.     length += strlen( addition );
  70.     temp = new char[length + 1];   // Allocate new buffer
  71.     strcpy( temp, buf );           // Copy contents of old buffer
  72.     strcat( temp, addition );      // Append new string
  73.     delete buf;                    // Deallocate old buffer
  74.     buf = temp;
  75. }
  76.  
  77. // ---------- Destructor for a String
  78. String::~String()
  79. {
  80.     delete buf;   // Works even for empty String; delete 0 is safe
  81. }
  82.  
  83.