Translations of this page?:

String operators

Syntax:

    #include <string>
    bool operator==(const string& c1, const string& c2);
    bool operator!=(const string& c1, const string& c2);
    bool operator<(const string& c1, const string& c2);
    bool operator>(const string& c1, const string& c2);
    bool operator<=(const string& c1, const string& c2);
    bool operator>=(const string& c1, const string& c2);
    string operator+(const string& s1, const string& s2 );
    string operator+(const Char* s, const string& s2 );
    string operator+( Char c, const string& s2 );
    string operator+( const string& s1, const Char* s );
    string operator+( const string& s1, Char c );
    string& operator+=(const string& append);
    string& operator+=(const Char* append);
    string& operator+=(const Char  append);
    ostream& operator<<( ostream& os, const string& s );
    istream& operator>>( istream& is, string& s );
    string& operator=( const string& s );
    string& operator=( const Char* s );
    string& operator=( Char ch );
    Char& operator[]( size_type index );
    const Char& operator[]( size_type index ) const;

C++ strings can be compared and assigned with the standard comparison operators: ==, !=, <=, >=, <, >, and =. Performing a comparison or assigning one string to another takes linear time.

Two strings are equal if:

  1. Their size is the same, and
  2. Each member in location i in one string is equal to the the member in location i in the other string.

Comparisons among strings are done lexicographically.

In addition to the normal container operators, strings can also be concatenated with the + operator and fed to the C++ I/O stream classes with the << and >> operators.

For example, the following code concatenates two strings and displays the result:

   string s1 = "Now is the time...";
   string s2 = "for all good men...";
   string s3 = s1 + s2;
   cout << "s3 is " << s3 << endl;

Furthermore, strings can be assigned values that are other strings, character arrays, or even single characters. The following code is perfectly valid:

   char ch = 'N';
   string s;
   s = ch;

Individual characters of a string can be examined with the [] operator, which runs in constant time.

Related Topics: c_str, compare, data

 
• • • IndexRecent changesRSScc