------------------------------------------------------------------------------
MC logo
C++ Strings
[^] CSc 220 Home
------------------------------------------------------------------------------
[Introduction] [Boolean and Control] [Functions] [Arrays and Pointers] [Dynamic Arrays] [Array Errors] [Command Array] [Standard Containers] [Structs and Classes] [Automatic Pointer] [Multi-File Programs] [Copying Objects] [Templates] [Inheritance] [Plain C I/O] [Type Odds And Ends] [Plain C Strings] [File I/O]
[Standards] [Programming Environment] [Hello, World!] [Hello Again, World!] [Identifiers] [Constants] [Average of Three] [Basic Types] [Shortcut Operators] [Increment Operators] [C++ Strings]
str.cc
#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;
}

This excellent string facility was introduced for C++. The string facility used in in plain C is peculiar, and we'll save it for later.

One new symbol we have not seen before is the ::. It is called the scope resolution operator, and we'll see more of it later. It is used to specify a name inside a larger naming scope, such as a class. Here, it refers to the constant named npos which is inside the class string.

One thing to get used to is that the C++ libraries do not use the Java convention of capitalizing class names. Hence, the name is string, not String.