Recent Changes - Search:

Coding C++

Computing

Container: std::string

Trail Index | Containers | Container String

A piece of text, or "string", is not, contrary to intuition, a "simple" type, but a sequence of characters.

The std::string container offers a flexible, assisted handling of strings.

/*
 * Container: std::string
 *
 * A piece of text, or "string", is not, contrary to intuition,
 * a "simple" type, but a sequence of characters.
 *
 * The std::string offers a flexible, assisted
 * handling of strings.
 */


#include <iostream>
#include <string>

int main() {
    using std::cout;
    using std::endl;

    // constructor, assignment
    std::string header="x, f(x)";
    cout<<header<<" (size="<<header.size()<<")\n";
   
    // assign a new value
    header="X, f(x)";

    // append text to the string
    header+=", f2(x)";
    cout<<header<<endl;

    // find a string
    const size_t pos=header.find("f2");
    cout<<" f2 found at "<<pos<<" - the first character is at pos=0\n";
    cout<<" character at [1]:"<<header[1]<<endl;

    // substring
    cout<<" substr(pos,2):"<<header.substr(pos,2)<<endl;

    // comparison
    if (header.substr(3,2)=="f(") {
        // replace, even with a string of different length
        header.replace(3,2,"Function(");
    }
    cout<<header<<endl;

    /*
     * BUT pay attention, using literal strings
     * (those in "") can be tricky:
     */

    std::string foot;
    //foot="Total "+"------------------"; // does not compile
    // at least one of the elements in the sum MUST be an explicit string!
    foot="*"+std::string("Total ")+"--------------------"+" *****";
    cout<<foot<<endl;
}

< Container Vector | Trail Index | Header Files >

Edit - History - Print - Recent Changes - Search
Page last modified on April 11, 2007, at 12:13 am