------------------------------------------------------------------------------
MC logo
C++ Strings
[^] Code Examples
------------------------------------------------------------------------------
<<Increment Operators str.cc Boolean Operations>>
#include <iostream>
#include <string>

using namespace std;

main()
{
        // Get some parts of speech, and combine them.
        cout << "Proper Noun? ";
        string res;
        cin >> res;

        cout << "Transitive Verb? ";
        string s;
        cin >> s;
        res += " " + s + " the ";

        cout << "Noun? ";
        cin >> s;
        res += s;

        cout << "Adverb? ";
        cin >> s;
        res += " " + s + ".";

        // Check this one.
        if(s.substr(s.length() - 2, 2) != "ly")
                cout << "Hmmm.  Adverbs _usually_ end in \"ly.\"" << endl;

        cout << "Useless sentence: " << res << endl;

        int pos = res.find("q q");
        if(pos != string::npos)
                cout << "Wow! Your sentence contains q, space, q "
                     << "in position " << pos << ".\n"
                     << "  How likely is that?" << endl;
}

The C++ string facility is very good. Later in the term, we will talk about the rather quirky string facility of plain C, and discover that C++ loads better. The C++ string facility is reminiscent of Java's, but has many differences. Some are:

One other unfamiliar thing in the program is the name string::npos. This is simply a named constant integer value declared in the standard library's string class. (It's probably -1, but I haven't tried to find out.) As we will see much later when we get to classes, C++ uses the :: notion to select members of a class, and reserves the dot for members of an object. Java uses the dot for both purposes.

And one final warning: in Java, double-quoted constants are strings. In C++, they are not. (As for what they are, and why, you must wait.) In most cases, conversion to string is automatic, but if you get mysterious errors, say string("whatever") to make an explicit conversion.

Reading: pp. 49-53
<<Increment Operators Boolean Operations>>