home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 10 Tools / 10-Tools.zip / snip9707.zip / STR.DOC < prev    next >
Text File  |  1997-07-05  |  45KB  |  1,059 lines

  1. +++Date last modified: 05-Jul-1997
  2.  
  3. TITLE
  4.  
  5.     class str
  6.  
  7. DESCRIPTION
  8.  
  9.     A simple but highly useful C++ string class
  10.  
  11. FILES
  12.  
  13.     str.h     class str definition
  14.     str.cpp   class str implementation
  15.  
  16. AUTHOR
  17.  
  18.     David Nugent
  19.  
  20. CONTACT
  21.  
  22.     FidoNet 3:632/348,
  23.     davidn@csource.pronet.com
  24.     PO Box 352,
  25.     Doveton, VIC, Australia
  26.     Voice +61-3-793-2728
  27.  
  28. STATUS
  29.  
  30.     Donated to the public domain, no restrictions on any use
  31.  
  32. SYNOPSYS
  33.  
  34.     class str is a simple yet powerful C++ string class,
  35.     providing many forms of conversions (from other base
  36.     types) to strings and a large variety of manipulators,
  37.     making it very useful as a stand-alone string class, for
  38.     output formatting with iostreams, for cheap copying,
  39.     concatenation and splitting operations, as a general
  40.     purpose class useful in data presentation and line-based
  41.     parsing.
  42.  
  43. GENERAL STRUCTURE
  44.  
  45.     class str is designed to be small, which makes it a
  46.     practical data type which can be used in large arrays
  47.     even on small memory systems.
  48.  
  49.     In addition, the typical implementation will result in a
  50.     much smaller str again if "VIRTUAL_DESTRUCTOR" is not
  51.     enabled, which prevents the destructor str::~str() from
  52.     being declared virtual, avoiding generation of a vtable
  53.     and vtable pointer for the class. Without a vtable
  54.     pointer, class str on most implementations is generally
  55.     the same size as sizeof() a data pointer, ie. as cheap
  56.     and small as a char*. The disadvantage of not making the
  57.     destructor virtual is that this places some limitations
  58.     on use of derived classes - however these are not severe,
  59.     and the main benefits of code reuse are still available
  60.     even without a virtual destructor. If a derived class
  61.     allocates resources, however, some care should be taken
  62.     to avoid upcasts if at all possible to ensure that the
  63.     correct destructor is called.
  64.  
  65.     These limitations are circumvented by defining
  66.     VIRTUAL_DESTRUCTOR to any non-zero value, with the
  67.     disadvantage that an object of class str will (usually)
  68.     be twice as big.
  69.  
  70.     Reference String
  71.  
  72.     Class str itself contains a single data member, being a
  73.     pointer to an internal "reference string". Reference
  74.     strings (embodied in class refstr) contains the actual
  75.     string data, and provides a mechanism for cheap copy and
  76.     assignment - instead of copying the data each time, more
  77.     than one str object is allowed to reference the same
  78.     physical data, and delays copying until one of the str
  79.     objects is modified, at which time a new refstr object is
  80.     created and copied from the old, and only that copy
  81.     changed. In many situations, that copy is never
  82.     modified, so physically copying of the string data never
  83.     becomes necessary, saving both in execution time and memory.
  84.  
  85.     The following diagram shows how 3 str objects share the
  86.     same reference string:
  87.  
  88.         str string1("This is a string");    // const char * __ctor
  89.         str string2(string1);               // str const & __ctor
  90.         str string3 = string1;              // str const & __ctor
  91.  
  92.     At this point, the relationship of these three objects and
  93.     the internal refstr is:
  94.  
  95.         string1
  96.             refstr  --.            refs   = 3
  97.         string2        \           length = 16
  98.             refstr  ------ refstr1 size   = 32
  99.         string3        /           data   = This is a string\0.....\0
  100.             refstr  --'
  101.  
  102.     The reference container object contains a counter for the
  103.     number of times the object is referenced by the str
  104.     wrapper. Any attempt to modify a refstr via any string
  105.     object while the number of references exceeds 1 results
  106.     in the refstr first being copied and the original left
  107.     untouched apart from the reference count being
  108.     decremented. Modifications are made on the copy only,
  109.     which has a reference count of 1.
  110.  
  111.     If, for example, string3 were to be modified by the
  112.     string " 3" being added (concatenated) to it, the diagram
  113.     would then look like:
  114.  
  115.         string1
  116.             refstr  --.
  117.         string2        -- refstr1 2/16/32/This is a string\0.....\0
  118.             refstr  --'
  119.         string3
  120.             refstr  ----- refstr1 1/18/32/This is a string 3\0...\0
  121.  
  122.  
  123.     Reference strings are a variable sized object. Size
  124.     variations of refstr objects are handled via a placement
  125.     operator new, which causes an additional amount of memory
  126.     to be allocated for the string data itself. Members of
  127.     class refstr (refs, length size, flags) coexist in memory
  128.     contiguous with the data itself, which is appended to the
  129.     end. Reference to and calculation of offsets of the data
  130.     itself is handled by wrapper functions in class refstr.
  131.  
  132.     The use of reference strings in this case provides a data
  133.     type which is almost always cheaper than using references
  134.     for parameter passing. For example, given two functions:
  135.  
  136.         void hello1(str x);
  137.         void hello2(str & x);
  138.  
  139.         str mystring("Hello world");
  140.  
  141.         hello1(mystring);
  142.         hello2(mystring);
  143.  
  144.     While the actual call to function hello2() is slightly
  145.     cheaper since it involves passing reference only, the
  146.     code within hello1 will not have to deal with the
  147.     additional indirection. Also the parameter passed to
  148.     hello1() may be freely modified without affecting the
  149.     original string even if both variables (the original and
  150.     the copy passed on the stack) initially reference the
  151.     same physical reference string.
  152.  
  153.     Pre-allocated size
  154.  
  155.     Note that by default, strings have a pre-allocated
  156.     internal size of at least STDLEN, which is defined in
  157.     str.cpp, the implementation file. This can be overridden
  158.     as desired using the additional optional parameter for
  159.     most of the class constructors. As shipped, the default
  160.     size of the memory allocated for the data in a refstr
  161.     object, unless overridden by the constructor, is 32
  162.     bytes. This amount is automatically grown to accommodate
  163.     insertions and concatenations (see the internal function
  164.     _chksize() for details).
  165.  
  166.     Preallocating memory for strings leads to efficiencies in
  167.     string manipulation, avoiding having to call for
  168.     reallocation for trivial modification.
  169.  
  170.     Conversions
  171.  
  172.     To accommodate conversion of a str object to a C style
  173.     'string' (a variable length char array with a NUL
  174.     terminator), class refstr is maintained at least one byte
  175.     larger than the amount required to contain the exact
  176.     string length. This fixes the overhead of adding the NUL
  177.     terminator as required rather than the overhead being
  178.     dependent on allowing the refstr object to become larger
  179.     in order to accommodate it if needed. Note that although
  180.     this additional byte is maintained, the string is NOT
  181.     NECESSARILY NUL TERMINATED, and that is exactly why the
  182.     c_str() member assures that it is. Dealing with the data
  183.     in this way and maintaining a separate length variable in
  184.     class refstr tends to eliminate any possibility of
  185.     continually scanning the string to determine length, as
  186.     is typical of a lot of C and C++ code which uses char*'s.
  187.     The member function to obtain the string length is a very
  188.     cheap operation.
  189.  
  190.     Conversion to char const *
  191.  
  192.     Class str provides no automatic type conversion operators
  193.     which are a common feature of many string classes. This
  194.     was considered far too dangerous to implement, as it can
  195.     occasionally cause invalid memory access - modification
  196.     or reading of string data which no longer 'exists'.
  197.     Instead, this functionality was moved to memory c_str(),
  198.     which must be explicitly called and yet still has a few
  199.     caveats. See notes under the explanation of c_str() below.
  200.  
  201.     Maximum string size
  202.  
  203.     For compactness, the maximum size of a string is fixed at
  204.     32K, even on 32-bit systems. This is a design feature
  205.     intended to meet the intended use of this class.
  206.     Manipulation of larger buffers is best done with classes
  207.     designed for this; the algorithms incorporated in class
  208.     str are not at all optimised for large text buffer
  209.     manipulation.
  210.  
  211.     Binary strings
  212.  
  213.     Because class str is not dependent on a terminating NUL,
  214.     it can be used for manipulation of binary strings. Note,
  215.     however, that any conversion to char const * via c_str()
  216.     will negate this advantage if the string contains a NUL -
  217.     a pointer to the string data may still be obtained by
  218.     c_str() or (since the NUL is not expected) c_ptr() which
  219.     is slightly cheaper.
  220.  
  221.  
  222. DESCRIPTION OF MEMBERS
  223.  
  224.     PUBLIC INTERFACE
  225.  
  226.     Class str was written primarily for practical use where
  227.     strings are most often used in other languages - data
  228.     presentation. After all, a string is not a computational
  229.     entity, but (usually) one which contains data that is
  230.     manipulated and presented in some way to a human, or at
  231.     least readable by machine or human.
  232.  
  233.     Consequently, the emphasis of members included in the
  234.     class provide direct conversion of built-in types to
  235.     strings via a large number of constructors. For
  236.     conversion from other classes, it is suggested that an
  237.     "operator str() const" be implemented for the class,
  238.     allowing a string to be directly created from it.
  239.  
  240.     Formatting output using class str, even with iostreams,
  241.     is much more easily done with class str than with
  242.     somewhat more clumsy iomanipulators. Padding, filling and
  243.     justification functions are all provided and are easy,
  244.     intuitive and safe to use, even with temporaries.
  245.     Moreover, str's are perfect for formatting before
  246.     insertion into an ostream - some manipulators, such as
  247.     width (via setw()), operate only on the next insertion,
  248.     and formatting within a string variable ensures that one
  249.     entire object is inserted in one insertion, therefore
  250.     respecting the state of the stream. Similarly, stream
  251.     justification, fill and other characteristics do not need
  252.     to be saved, set and restored around insertion operations.
  253.  
  254.     Constructors
  255.  
  256.     class str defines a default constructor, providing
  257.     convenient support for allocation of arrays. All other
  258.     constructors provide some form of conversion, including
  259.     conversion of char*'s, all built-in integral types
  260.     (short, int, long and unsigned versions thereof), and all
  261.     forms of char. Note that char is not handled as an
  262.     integral. Conversion of integral types allows
  263.     specification of a radix, so support for non- decimal
  264.     numeric conversions other than base 10 are fully supported.
  265.  
  266.     str (void);
  267.  
  268.         Default constructor. Allocates a zero-length string
  269.         with an internal size determined by the pre-allocated
  270.         length. In almost all cases it is more efficient to
  271.         use one of the initialising constructors if possible.
  272.  
  273.             str mystring;
  274.  
  275.     str (char const * s, short len =-1);
  276.     str (unsigned char const * s, short len =-1);
  277.     str (signed char const * s, short len =-1);
  278.  
  279.         These constructors provide conversion from C strings.
  280.         The length parameter allows extraction of only a
  281.         portion of a string (sub- string). The default value
  282.         of -1 assumes that the source string is NUL terminated.
  283.  
  284.             str mystring("Hello world!");
  285.             str mystring = "Hello world!");
  286.             str mystring("Hello world!", 5);    // Contains 'Hello' only
  287.  
  288.     str (int val, int radix =10);
  289.     str (unsigned int val, int radix =10);
  290.     str (short val, int radix =10);
  291.     str (unsigned short val, int radix =10);
  292.     str (long val, int radix =10);
  293.     str (unsigned long val, int radix =10);
  294.  
  295.         These provide automatic conversion for all integral
  296.         types with a default radix of 10. Negative values of
  297.         signed types will cause the resulting string to have
  298.         a leading '-' sign.
  299.  
  300.         For a non-decimal radix, no indication of the
  301.         number's base is automatically inserted. If you wish
  302.         to use "0x" for hexadecimal numbers, for example, you
  303.         will need to use one of the insert() members. When
  304.         using a non-decimal radix, it is highly recommended
  305.         that one of the unsigned converters be used to
  306.         prevent generation of the sign prefix.
  307.  
  308.             str mystring(10999);        // result '10999'
  309.             str mystring(255,16);       // result 'ff'
  310.             str mystring = -14587;      // result '-14587'
  311.             str mystring = (unsigned)-1;// implementation dependent
  312.  
  313.     str (char c);
  314.     str (unsigned char c);
  315.     str (signed char c);
  316.  
  317.         These constructors are not integral conversions but
  318.         convert a single character into a string with a
  319.         length of 1.
  320.  
  321.             str mystring('g');          // 'g'
  322.             str mystring = 'k'          // 'k'
  323.  
  324.     str (str const & s);
  325.  
  326.         This is the copy constructor. Note that this causes
  327.         the new string to be initialised with the same refstr
  328.         as contained by the string being copied, and so is
  329.         the cheapest constructor available.
  330.  
  331.             str mystring1 = "Hello world!";
  332.             str mystring2 = mystring1;  // 'Hello world!'
  333.             str mystring3(mystring1);   // 'Hello world!'
  334.  
  335.     ~str (void);
  336.  
  337.         Class destructor. This will deallocate the contained
  338.         reference string if it is the only string which
  339.         references it, otherwise only the reference strings
  340.         'reference count' is decremented.
  341.  
  342.     str & clear(void);
  343.  
  344.         This member provides the ability to quickly clear the
  345.         contents of a string. Not that if the contained
  346.         reference string is not referenced by any other str
  347.         object, the length is reduced to zero but the string
  348.         size (size of the actual refstr) is untouched. This
  349.         makes this function suitable when using a string as a
  350.         temp variable - it will grow to accommodate the
  351.         largest item placed into it and therefore not require
  352.         constant reallocation in a loop for example, except
  353.         where the items are made progressively bigger.
  354.  
  355.             str         tempstr;
  356.             ifstream    input("myfile.txt");
  357.  
  358.             while(!input.rdstate())
  359.             {
  360.                     // Clear the string and read next line
  361.                 input >> tempstr.clear();
  362.                     // Process the string ...
  363.  
  364.     str & operator= (str const & s);
  365.     str & operator= (char const * s);
  366.     str & operator= (char c);
  367.     str & operator= (unsigned char const * s);
  368.     str & operator= (signed char const * s);
  369.  
  370.         Assignment operators do pretty much the same as the
  371.         constructors noted above.
  372.  
  373.         Assignment operators for integral conversions are not
  374.         provided simply because this is already taken care of
  375.         by constructors, and their functionality would be
  376.         otherwise duplicated. To assign an integral type,
  377.         therefore, simply cast the right hand side first:
  378.  
  379.             str     myintstr;
  380.  
  381.             myintstr = str(10);
  382.  
  383.         This also allows specification of a radix if desired
  384.         and does pretty much what would otherwise occur
  385.         internally anyway.
  386.  
  387.     short length (void) const;
  388.  
  389.         Returns the length of the string, simply by reading
  390.         the field in the contained reference string.
  391.  
  392.             str result = "The string 'rest' is exactly ";
  393.             str rest   = " characters long";
  394.  
  395.             result << rest.length() << rest;
  396.             // 'The string 'rest' is exactly 16 characters long'
  397.  
  398.     short size (void) const;
  399.  
  400.         This returns the internal size of the string - ie.
  401.         the maximum number of characters (less 1) which can
  402.         be assigned to the string before it needs to be
  403.         reallocated.
  404.  
  405.         This is usually of little or no value to the user of
  406.         the str class as strings are grown to accommodate.
  407.         However, it may be helpful in some circumstances for
  408.         optimisation purposes.
  409.  
  410.     str & operator<< (char const * s);
  411.     str & operator<< (unsigned char const * s);
  412.     str & operator<< (signed char const * s);
  413.     str & operator<< (str const & s);
  414.     str & operator<< (int val);
  415.     str & operator<< (unsigned int val);
  416.     str & operator<< (short val);
  417.     str & operator<< (unsigned short val);
  418.     str & operator<< (long val);
  419.     str & operator<< (unsigned long val);
  420.     str & operator<< (char c);
  421.     str & operator<< (unsigned char c);
  422.     str & operator<< (signed char c);
  423.  
  424.         These operators provide string concatenation. Values
  425.         on the right hand side of a << operation are appended
  426.         to the end of the string, much like stream insertion
  427.         operators. Integral types larger than char may also
  428.         be concatenated and are automatically converted to
  429.         str prior concatenation.
  430.  
  431.             str mystr "Now is the ";
  432.  
  433.             mystr << "time for all good men.\n"
  434.                   << 10 << " times " << 10 << '=' << 100;
  435.  
  436.  
  437.     char const & operator[] (short pos) const;
  438.     char & operator[] (short pos);
  439.  
  440.         The subscript operators provides a way of referencing
  441.         individual characters within a str object, similar to
  442.         usual C string semantics. There are, however, some
  443.         differences:
  444.  
  445.             Negative indices in the range -length() to -1
  446.             allows reference to character positions
  447.             calculated from the end of the string, for
  448.             example mystr[-1] addresses the last character in
  449.             the string, mystr[-2] addresses the character
  450.             previous to that etc.
  451.  
  452.             For the const operator (used on the rhs of an
  453.             expression) indices specified which are outside
  454.             of the allowed range of -length() to length()
  455.             return a reference to the character position at
  456.             length(), ie. the end of the string.
  457.  
  458.             The non-const operator (used on the lhs of an
  459.             assignment) indices specified which are outside
  460.             the range of -length() to length() cause the
  461.             string to be extended and space padded.
  462.  
  463.     char * c_ptr() const;
  464.     char const * c_str() const;
  465.     unsigned char const * u_str() const;
  466.     signed char const * s_str() const;
  467.  
  468.         These members provide direct pointers to the string
  469.         data itself. They are only guaranteed to remain valid
  470.         while the string itself remains unmodified!
  471.  
  472.         c_ptr() does not NUL terminate the string and returns
  473.         a non-const pointer, and therefore may be used to
  474.         modify the string. The responsibility for ensuring
  475.         that memory outside of that owned by the string is
  476.         entirely the programmers'. This function is
  477.         particularly useful in manipulation of binary strings.
  478.  
  479.             str     mybinstr;
  480.  
  481.             mybinstr.left(10,0);
  482.                 // Grows string to 10 bytes, zero filled.
  483.             mybinstr.c_ptr()[3] = 6;
  484.                 // places 6 (^F) into the 4th position
  485.                 // This is equivalent to mybinstr[3] = 6,
  486.                 // however in some contexts, c_ptr() may
  487.                 // be simpler to deal with (for example when
  488.                 // using memcpy() to fill the string
  489.  
  490.         c_str(), u_str() and s_str() provide const pointers
  491.         to the string in order to allow its use as a normal C
  492.         string. c_str() returns a const pointer to char, the
  493.         sign of which is implementation defined, u_str()
  494.         returns a pointer to unsigned char, and s_str()
  495.         returns a pointer to signed char.
  496.  
  497.         It cannot be emphasised enough that care must be
  498.         taken by the user of these members that a string is
  499.         NOT TO BE MODIFIED IN ANY WAY while a pointer
  500.         returned by any of them is in use. Modification of
  501.         the string may well cause it's relocation in memory,
  502.         and any pointer will be left undefined. To avoid this
  503.         deficiency, a method of 'freezing' the string (a la
  504.         strstreams) was considered; however, this is
  505.         generally less convenient and leads to clumsy syntax
  506.         in most situations, and the existence of this caveat
  507.         was considered to be the best compromise. For this
  508.         reason also no automatic conversion to "char const *"
  509.         has been implemented since the compiler would then be
  510.         provided with a means of extracting a "char const *"
  511.         whenever it wished, making it much less easy to guard
  512.         against.
  513.  
  514.             void
  515.             func(str mystr);
  516.             {
  517.                 char    myarray[128];
  518.  
  519.                 strncpy(myarray, mystr.c_str(), 127);
  520.                 myarray[127] = '\0';
  521.                 // ...
  522.  
  523.  
  524.     int copy(char * dest, short maxlen =-1) const;
  525.  
  526.         This member allows a convenient way of copying a str
  527.         object into a char array. 'maxlen' specifies the
  528.         maximum length of the destination array - you would
  529.         be well advised to use this. The default value of -1
  530.         causes the length to be disregarded and the length of
  531.         the contained string used instead.
  532.  
  533.         After copying, the destination string is guaranteed
  534.         to be NUL terminated. If maxlen is specified, then up
  535.         to maxlen-1 characters are copied to the memory
  536.         location pointed to by 'dest' and a terminating NUL
  537.         added. If the str object is less than (maxlen-1)
  538.         characters long, the terminating NULL will be placed
  539.         at dest+length().
  540.  
  541.         str::copy() should be used in preference to
  542.         str(n)copy and str::c_str() as it will almost always
  543.         be more efficient, and provides the functionality of
  544.         strncpy() without the need to explicitly terminate
  545.         the string with NUL. Compare the following to the
  546.         previous example for c_str().
  547.  
  548.             void
  549.             func(str mystr)
  550.             {
  551.                 char    myarray[128];
  552.  
  553.                 mystr.copy(myarray, 128);
  554.                 // ...
  555.  
  556.     short insert (short pos, char const * s, short len =-1);
  557.     short insert (short pos, str const & s);
  558.     short insert (short pos, unsigned char const * s, short len =-1);
  559.     short insert (short pos, signed char const * s, short len =-1);
  560.     short insert (short pos, char c);
  561.     short insert (short pos, unsigned char c);
  562.     short insert (short pos, signed char c);
  563.  
  564.         Insertion operators provide a way to safely insert
  565.         other strings (C strings or str objects) into a str
  566.         object. 'pos' is specified as the number of bytes
  567.         offset from the start of the string. Any negative
  568.         value of pos or values which exceed the current
  569.         length of the string causes concatenation to the end
  570.         (ie. insertion after the last character).
  571.  
  572.         For insertion of C strings, the len argument provides
  573.         the ability to insert only a portion of a string. If
  574.         the default argument or -1 is used, the NUL
  575.         terminator will be used instead to determine the
  576.         source string length.
  577.  
  578.             str mystr("time for all good men.");
  579.  
  580.             mystr.insert(0,"Now is the ");
  581.                 // 'Now is the time for all good men.'
  582.  
  583.     short remove (short pos =0, short len =-1);
  584.  
  585.         The str::remove() member provides the ability to
  586.         excise a portion of a string. If used with the
  587.         default arguments, the string is entirely cleared
  588.         (but not reallocated so, like str::clear(), the
  589.         memory allocated to the string is left the same).
  590.         'pos' defaults to 0, being the start of the string.
  591.         len's default value of -1 causes the string's length
  592.         to be used, in which case all characters at and
  593.         following the position 'pos' are removed.
  594.  
  595.             str mystr = "The quick brown fox jumps over the lazy dog";
  596.  
  597.             mystr.remove(10, 6);
  598.                 // 'The quick fox jumps over the lazy dog'
  599.             mystr.remove(19);
  600.                 // 'The quick fox jumps'
  601.             mystr.remove();
  602.                 // '' - blank.
  603.  
  604.     short replace (short pos, char const * s, short clen =-1, 
  605.                                                           short len =-1);
  606.     short replace (short pos, str & s, short clen =-1);
  607.     short replace (short pos, unsigned char const * s, short clen =-1, 
  608.                                                           short len =-1);
  609.     short replace (short pos, signed char const * s, short clen =-1,
  610.                                                           short len =-1);
  611.     short replace (short pos, char c, short clen =-1);
  612.     short replace (short pos, unsigned char c, short clen =-1);
  613.     short replace (short pos, signed char c, short clen =-1);
  614.  
  615.         These members do the equivalent of str::remove() and
  616.         str::insert() in one operation. 'pos' specifies the
  617.         position at which replacement is to start, 'clen'
  618.         specifies the number of characters to replace in the
  619.         original string (ie. how many to remove before
  620.         inserting), 's' (or 'c') is the string to insert, and
  621.         where applicable, 'len' is the number of characters
  622.         from 's' which are to replace the characters removed.
  623.         If 'len' is -1, then the number of characters used is
  624.         determined by the NUL terminator in 's' (ie. the
  625.         result of strlen()). If 'clen' is -1, then all
  626.         characters up until the end of the string are replaced.
  627.  
  628.         Using str::replace() is far more efficient than using
  629.         remove() then insert().
  630.  
  631.             str mystr = "The quick brown fox jumps over the lazy dog".
  632.  
  633.             mystr.replace(10, "black", 5);
  634.                 // 'The quick black fox jumps over the lazy dog'
  635.  
  636.     str & left (short len, char padch =' ');
  637.     str & right (short len, char padch =' ');
  638.     str & mid (short pos, short len, char padch =' ');
  639.  
  640.         These members mutate the string and provide string
  641.         truncation and padding.
  642.  
  643.         Firstly, please note that these functions do NOT work
  644.         in the same manner as the BASIC style string
  645.         functions of the same name. The functionality is
  646.         similar, but certainly not identical.
  647.  
  648.         These functions, left() and right() in particular,
  649.         will probably be used mostly for string formatting.
  650.         There are non-member functions of the same name
  651.         ::left(str, len, pad) and ::right(str, len pad) which
  652.         provide the same functionality, but rather than
  653.         mutating the string itself, instead returns a copy of
  654.         the original string appropriately modified.
  655.  
  656.         While these functions will truncate a string if the
  657.         string()'s length exceeds 'len', they will also pad
  658.         the string with 'padch' to extend it to 'len' if it
  659.         is shorter. The left() member extends the string on
  660.         the right hand side while the right() member extends
  661.         it to the left(). mid() removes any characters to the
  662.         left of the starting position and from that point
  663.         works pretty much like left(), padding on the right
  664.         if required.
  665.  
  666.             str mystr = 2000;
  667.  
  668.             cout << "There are " << mystr.right(8) << " pieces;
  669.                 // Output:
  670.                 // 'There are     2000 pieces'
  671.             str name = "David Nugent"
  672.             str addr = "davidn@csource.pronet.com"
  673.             str fund = 0;
  674.  
  675.             cout << left(name, 25)
  676.                  << left(addr, 32)
  677.                  << right(fund, 8)
  678.                  << endl;
  679.                     // Output padded appropriately.
  680.                     // Note that by using the global functions,
  681.                     // the original string remains unmodified
  682.  
  683.     str substr(short start, short len =-1) const;
  684.  
  685.         substr() returns a substring, much like mid() except
  686.         that no padding is provided. substr() in fact
  687.         provides similar functionality to BASICS's left(),
  688.         right() and mid() in one function.
  689.  
  690.         If 'start' is negative, the actual starting position
  691.         is calculated from the end of the string, otherwise
  692.         the offset is from the left. If 'len' is negative or
  693.         larger than the length of the string, all characters
  694.         to the right of the specified start position are
  695.         returned in the resulting string. The returned string
  696.         is never padded.
  697.  
  698.             str mystr = "This shows how the str::substr() member works";
  699.  
  700.             cout << "mystr.substr(19,13)=" << mystr.substr(19,13)
  701.                  << '\n'                    // 'str::substr()'
  702.                  << "mystr.substr(41)=" << mystr.substr(41)
  703.                  << '\n'                    // 'works'
  704.                  << "mystr.substr(-5)=" << mystr.substr(-5)
  705.                  << endl;                   // 'works'
  706.  
  707.     short removech (char const * clist ="\r\n");
  708.  
  709.         This member provides a convenient method of removing
  710.         all occurrences of a set of characters from a string.
  711.         The default character list removes end of line
  712.         characters. The value returns represents the number
  713.         of characters removed (ie. the amount by which the
  714.         length has been decreased).
  715.  
  716.             str mystr = "Testing\n";
  717.  
  718.             mystr.removech();           // 'Testing'
  719.             mystr.removech("ing");      // 'Test'
  720.  
  721.     short countch (char const * clist);
  722.  
  723.         str::countch() returns the number of times any
  724.         character from the supplied character list occurs in
  725.         the string. This can be used to test the presence of
  726.         one or more characters.
  727.  
  728.             str mystr = "testing\n";
  729.  
  730.             cout << "The letter 't' appears in '"
  731.                  << mystr << "' " << mystr.countch("t") << " times."
  732.                  << endl;
  733.  
  734.     bool operator== (str const & s) const;
  735.     bool operator== (char const * s) const;
  736.     bool operator== (unsigned char const * s) const;
  737.     bool operator== (signed char const * s) const;
  738.     bool operator!= (str const & s) const;
  739.     bool operator!= (char const * s) const;
  740.     bool operator!= (unsigned char const * s) const;
  741.     bool operator!= (signed char const * s) const;
  742.     bool operator< (str const & s) const;
  743.     bool operator< (char const * s) const;
  744.     bool operator< (unsigned char const * s) const;
  745.     bool operator< (signed char const * s) const;
  746.     bool operator<= (str const & s) const;
  747.     bool operator<= (char const * s) const;
  748.     bool operator<= (unsigned char const * s) const;
  749.     bool operator<= (signed char const * s) const;
  750.     bool operator> (str const & s) const;
  751.     bool operator> (char const * s) const;
  752.     bool operator> (unsigned char const * s) const;
  753.     bool operator> (signed char const * s) const;
  754.     bool operator>= (str const & s) const;
  755.     bool operator>= (char const * s) const;
  756.     bool operator>= (unsigned char const * s) const;
  757.     bool operator>= (signed char const * s) const;
  758.     int compare (str const & s) const;
  759.     int compare (char const * s) const;
  760.     int compare (unsigned char const * s) const;
  761.     int compare (signed char const * s) const;
  762.  
  763.             [The 'bool' value returned by these functions
  764.             represents the boolean type passed recently by
  765.             the ANSI C++ committee - if not supported by your
  766.             compiler yet, it must be #defined explicitly. The
  767.             'bool' type has two possible values; False or
  768.             True - False is zero, True is non-zero. Unless
  769.             supported by the compiler, a bool value should
  770.             never be directly tested against 'True' as this
  771.             will often provide erroneous results where 'True'
  772.             has been defined as a specific non-zero value.]
  773.  
  774.         These functions provide basic string comparison
  775.         functionality. The basic compare() function returns
  776.         values comparable with strcmp() or stricmp(),
  777.         depending on the setting of the internal "case
  778.         sensitivity" flag maintained for each string.
  779.  
  780.         static void setdefaultcase (bool s = True);
  781.  
  782.         By default, each string is case sensitive. A static
  783.         member function provides the ability to set the
  784.         default flags for each string (currently only ICASE -
  785.         case insensitivity - is implemented), and will be
  786.         applied to all strings created after this is called.
  787.  
  788.         void setcase (bool s =True);
  789.  
  790.         Case sensitivity can be enabled or disabled for
  791.         individual strings by using str::setcase().
  792.         setcase(True) makes the string case sensitive - this
  793.         is normally the default, depending on whether the
  794.         set::setdefaultcase() function has been used - and
  795.         setcase(False) makes the string case INsensitive. In
  796.         comparing strings, if either one of the strings
  797.         compared is flagged as case insensitive, the
  798.         comparison is case insensitive. If both strings are
  799.         flagged as case sensitive, then the comparison is
  800.         case sensitive.
  801.  
  802.         Any of the str::compare() overloads returns a value <
  803.         0 if the current string is compares less than the
  804.         string argument, 0 if they are equal and >0 if the
  805.         string argument is greater than the current string.
  806.         If the comparison is case insensitive, the precise
  807.         value of comparisons for strings commencing with
  808.         ASCII values between 'Z' and 'a' (not inclusive)
  809.         depend on your vendor library's implementation of
  810.         stricmp(), specifically depending on whether strings
  811.         are converted to upper or lower case before
  812.         comparison of individual characters.
  813.  
  814.         The comparison operators ==, !=, <, >, >= and <= are
  815.         provided as short-hand notations of the built-in
  816.         str::compare() member.
  817.  
  818.             str mystr1("Hello WORLD!");
  819.             str mystr2("HELLO world!");
  820.  
  821.             if (mystr1 != mystr2)
  822.                 cout << "Comparison is case sensitive" << endl;
  823.             else
  824.                 cout << "Comparison is case insensitive" << endl;
  825.  
  826.             mystr1.setcase(False);  // Turn case sensitivity off
  827.  
  828.             if (mystr1 == mystr2)
  829.                 cout << mystr1 << " = " << mystr2 << endl;
  830.             if (mystr1 > "abcdef")
  831.                 cout << mystr1 << " is greater than abcdef" << endl;
  832.  
  833.     short strstr (str const & s) const;
  834.     short strstr (char const * s) const;
  835.     short strstr (unsigned char const * s) const;
  836.     short strstr (signed char const * s) const;
  837.  
  838.         This group of str::strstr() overloads provides a way
  839.         of doing simple substring searches within a str
  840.         object. As with comparison, the case of substrings is
  841.         determined by the case sensitivity of the string
  842.         being searched, and in the case of strstr(str const
  843.         &) also the case sensitivity of the substring being
  844.         searched for.
  845.  
  846.         While similar to the stdc library strstr, this
  847.         function returns the offset at which the substring is
  848.         found rather than a pointer to the found string - if
  849.         a pointer to the located string is desired, add the
  850.         offset to the return from c_str().
  851.  
  852.         A return value of -1 indicates that the substring was
  853.         not located - anything else is the offset at which
  854.         the substring starts.
  855.  
  856.  
  857.     PROTECTED INTERFACE
  858.  
  859.     This section deals with functions and data members
  860.     accessible from derived classes.
  861.  
  862.     In deriving classes from class str, please note the
  863.     comments in the above section "GENERAL STRUCTURE" which
  864.     deal with the issue of class str's virtual (or not)
  865.     destructor, and check the #define at the top of str.h. If
  866.     the destructor is defined as a virtual function, then you
  867.     can freely use and upcast a derived class to a str. If
  868.     not, then you should be careful how you deal with strings
  869.     classes derived from str, and if you upcast to class str,
  870.     ensure either that your derived class needs no destructor
  871.     to clear and deallocate resources, or that you implement
  872.     some means of garbage collecting for your derived class
  873.     (eg. use some form of resource tracking). The choice of
  874.     whether to make the destructor virtual or not is yours -
  875.     it is the only virtual function that is used in class
  876.     str, so consequently derived classes from str will
  877.     normally only add functionality rather than any serious
  878.     attempt at using polymorphism. str was not created with
  879.     polymorphism in mind.
  880.  
  881.     The protected interface of class str provides complete
  882.     access to the str object, including refstr, internal
  883.     reference string and members. Provided the user obey
  884.     certain rules, there should be no problem with this.
  885.     These rules are:
  886.  
  887.     o   A refstr is not exclusively "owned" by a string object
  888.         unless the reference count in the refstr is equal to
  889.         1. Mutation or modification of ANY sort of the refstr
  890.         pointed to by the strdata member must be guarded
  891.         against by a call to the protected member _chksize.
  892.         THIS MEANS ANY CHANGE WHATSOEVER NO MATTER HOW TRIVIAL.
  893.  
  894.     o   If you intend to append or insert data into the current
  895.         string, then you can call _chksize(?), where ? is the
  896.         final size you intend to use. As well as allocating a
  897.         new refstr object if the reference count exceeds on
  898.         and copying the old data to the new refstr,
  899.         _chksize() will ensure that the string data size is
  900.         large enough to accommodate anything that you wish to
  901.         do with it.
  902.  
  903.     o   When calling _chksize(), _never_ assume that any internal
  904.         pointer to data will remain valid across the call.
  905.         Either work with offsets only instead, or convert any
  906.         pointers to offsets from the previous start of string
  907.         to offsets and back again into pointers. One example
  908.         of this being done can be found in the implementation
  909.         of str::removech() in str.cpp.
  910.  
  911.     o   If you use _chksize() with a size, add 1 to the size
  912.         requested to ensure that the refstr is at least large
  913.         enough to hold one additional byte beyond the string
  914.         data itself. This additional byte allows for addition
  915.         of a NUL for conversions to char const* without
  916.         causing reallocations.
  917.  
  918.     o   Avoid calling _chksize() unless you really are going to
  919.         modify the string. Since _chksize() ensures mutually
  920.         exclusive ownership of the string data by the current
  921.         string object, it is pointless to cause loss of CPU
  922.         cycles and memory when in fact nothing is done. Once
  923.         the enclosed refstr is owned by a str object,
  924.         however, calling _chksize() causes little overhead
  925.         except when the string needs to be resized.
  926.  
  927.     o   _strinit() (either overload) needs to be used with care.
  928.         Don't call these unless you intend deallocating the
  929.         current strdata and have saved it, or have already
  930.         deallocated strdata - it is over-written and never
  931.         deallocated. The deallocation is entirely your
  932.         responsibility.
  933.  
  934.     static unsigned short default_flags;
  935.  
  936.         default_flags is the value passed to _strinit() during
  937.         string setup. You can override these flags if you
  938.         need to by calling _strinit() directly.
  939.  
  940.     refstr * strdata;
  941.  
  942.         strdata is the member which contains the address of the
  943.         reference string, which is in fact the internal
  944.         string entity which may be shared by multiple 'str'
  945.         objects. Before modifying this, or modifying the
  946.         object it points to, refer to the discussion
  947.         immediately before this.
  948.  
  949.     int _chksize (short sz =0);
  950.  
  951.         _chksize() forms pretty much the core of what manages
  952.         refstr() objects (_strinit() creates them, this
  953.         manages). _chksize() is responsible for two things:
  954.  
  955.             Once called during management of a str, _chksize()
  956.             ensures that the str has it's very own refstr
  957.             pointed to by strdata. This allows code to modify
  958.             the string without causing side- effects on other
  959.             strs which happen to reference the same data.
  960.  
  961.             _chksize() also does as its name implies - checks
  962.             the size of the refstr to ensure that it is large
  963.             enough to contain at least the number of bytes
  964.             stated by its parameter.
  965.  
  966.     int _concat (char const * s, short len =-1);
  967.  
  968.         This is the fundamental string concatenation routine.
  969.         All concatenation operators end up passing through
  970.         this one after conversion to char const*.
  971.  
  972.         Note that a serious limitation in using this function
  973.         in the previous release of this class has been
  974.         removed - _concat() now checks to see if the pointer
  975.         passed references it's own data (full string or
  976.         substring), and if so, first copies that substring
  977.         before performing the concatenation to ensure that
  978.         the pointer 's' remains valid. It is therefore now
  979.         possible to concatenate a string (or substring
  980.         thereof) it itself.
  981.  
  982.     int _compare (str const s) const;
  983.  
  984.         This is the fundamental string compare function.
  985.         Comments regarding the public interface for
  986.         str::compare() above apply.
  987.  
  988.     short _strstr (str const s) const;
  989.  
  990.         This is the fundamental substring search function.
  991.         Comments regarding the public interface for
  992.         str::_strstr() apply.
  993.  
  994.     void _strinit (char const * s =0, short slen =0, short siz =-1,
  995.                                unsigned short flgs =default_flags);
  996.     void _strinit (unsigned long val, bool positive, int radix);
  997.  
  998.         These functions are the initial allocators for new
  999.         refstr objects. The first is called by the second,
  1000.         and optionally allows a string to be initialised or
  1001.         set to a specific length according to the caller's
  1002.         requirements. The second _strinit() overload is for
  1003.         integral conversions. If signed numbers are passed to
  1004.         this function, you should already have converted them
  1005.         to absolute values and passed the sign in the boolean
  1006.         'positive' (True if positive, otherwise negative).
  1007.         'radix' is the base of the number used during the
  1008.         conversion.
  1009.  
  1010.     GLOBAL FUNCTIONS
  1011.  
  1012.     str.h contains prototypes for several functions defined at file
  1013.     scope with deal with strings. The philosophy used is that member
  1014.     functions are generally used to mutate a string, but the global
  1015.     equivalents of the same name return a new string, copied from the
  1016.     old and mutated, leaving the original str object untouched.
  1017.  
  1018.     In addition, iostream insertion and extraction operators provides
  1019.     a simple, intuitive and straight-forward interface to the iostreams
  1020.     library.
  1021.  
  1022.     str left (str s, short len, char padch =' ');
  1023.     str right (str s, short len, char padch =' ');
  1024.     str mid (str s, short pos, short len, char padch =' ');
  1025.  
  1026.         These are inline equivalents for the member functions of the same
  1027.         name. Each returns a mutation of the original string. Typically
  1028.         these are used for temporary formatting for streams etc.
  1029.  
  1030.             str mystream(100);
  1031.  
  1032.             cout << "      Cost Total\n"
  1033.                  << right(mystream, 10)
  1034.                  << ' '
  1035.                  << left(mystream, 10)
  1036.                  << endl;
  1037.  
  1038.     int compare(str s, str b);
  1039.     int compare(str s, char const * b);
  1040.     int compare(str s, unsigned char const * b);
  1041.     int compare(str s, signed char const * b);
  1042.  
  1043.         These provide comparison functions, and in some contexts
  1044.         may be easier to use than the str.compare() overloads.
  1045.  
  1046.     ostream & operator<< (ostream & os, str const & s);
  1047.     istream & operator>> (istream & is, str & s);
  1048.  
  1049.          These are the iostream interface operators. operator>>
  1050.          extracts a line of text from an input stream, removing
  1051.          the newline, if any. The string is automatically grown
  1052.          to accommodate input but will not shrink for smaller
  1053.          lines. Contents of the string prior an extraction
  1054.          operation are discarded.
  1055.  
  1056.          The insertion operator<< outputs the contents of the
  1057.          string, assumed to be a NUL terminated C string, to
  1058.          the stream.
  1059.