C++ Strings

The string class

#include <string> // different than <cstring> which is C's string.h

    std::string s1("hello");        // s1 is "hello"
    std::string s2(3, 'x');         // s2 is "xxx"
    std::string s3 = " world";      // calls copy constructor to make fresh copy of "world"
    std::string s4;                 // empty string "" (NOT a null variable!)
                                    // implicitly calls default constructor
    std::string s5(s2);             // calls copy constructor

String conversions

String representation & operations

    s = "wow"           //  for assignment of literals
    cin >> s            //  input from stream - stops at whitespace!
    cout << s           //  output to stream
    getline(is, s)      //  read to end of line from stream is, store in s
    s1 = s2             //  deep copy assignment 
                        //  or s1.assign(s2) s1.assign(s2, start, howmany)
    s1 + s2             //  string concatenation
    s1 += s2            //  same as s1 = s1 + s2, also same as s1.append(s2)
    == != < > <= >=     //  relational operators overloaded, they just work (no strcmp needed)

    s1.size() == s1.length() == number of characters
    s1.capacity()           // how many characters currently allocated (can increase, see reserve below)
    s1.max_size()                 // max for all strings
    s1.empty()                    // returns a bool
    s1.reserve(s1.length() + 5);  //changes capacity

    s1.substr(where, howmany);
    s1.compare(s2);  // like C's strcmp; most of the time use overloaded &lt; &gt; etc instead
    s1.c_str();  // get c-style string (null terminated character array)

Passing strings to functions