PTypes: string: operators

Top: Basic types: string: Operators

>     #include <ptypes.h>

>     class string {
>         // assignment
>         string& operator =(const char*);
>         string& operator =(char);
>         string& operator =(const string&);
>         friend void assign(string&, const char* buf, int len);

>         // concatenation
>         string& operator +=(const char*);
>         string& operator +=(char);
>         string& operator +=(const string&);
>         string  operator +(const char*) const;
>         string  operator +(char) const;
>         string  operator +(const string&) const;
>         friend  string operator +(const char*, const string&);
>         friend  string operator +(char c, const string&);

>         // comparison
>         bool operator ==(const char*) const;
>         bool operator ==(char) const;
>         bool operator ==(const string&) const;
>         bool operator !=(const char*) const;
>         bool operator !=(char c) const;
>         bool operator !=(const string&) const;

>         // indexed character access, 0-based
>         char& string::operator[] (int index);
>         const char& string::operator[] (int index) const;
>     }

The string class defines the following binary operators: assignment (=), concatenation (+), concatenation with assignment (+=) and comparison (==, !=). At least one of the operands (either left or right) must be of type string. Another operand can be one of the following: char, char* or string.

Indexed access operator allows to store or retrieve a value of an individual character. The index is 0-based. When compiled with either DEBUG or CHECK_BOUNDS conditional symbol, bounds checking is performed for the indexed access; if the index is out of bounds (i.e. less than 0 or equals to or greater than the length of the string), an unrecoverable error is raised. The non-debugging version of the library never checks for index overlfows, thus making your program somewhat faster but less safe.

Examples

>     string s1 = "abc", s2 = 'd', s3;

>     s3 = s1 + s2;
>     s2 += "ef";
>     s3[2] = 'B';

See also: Constructors/destructors, Typecasts, Manipulation, Conversion

PTypes home