In The Beginning...

We've been using strings in their literal form ("a string literal") since the very first program:

    #include <iostream>

    using namespace std;

    int main(void)
    {
        cout << "Hello World!"
             << endl;
        return 0;
    }

But up until we studied more of the standard libraries, we were only able to store single characters in a variable. When we heard about the string library, we learned about variables to store whole strings! (For a refresher, look back at those notes.)

A class In A Library

We've heard on and off about 'classes'. cin and cout are class type variables/objects. We know we're eventually going to learn to write our own class types. But first let's gain a little more experience with using classes that the standard library provides to us. One of these is the string class. It is found in the string library, oddly enough. So, to use the string class, we need to have:

    #include <string>

at the top of our program. Then, to declare a variable (or object) of type string, we simply use it like any other type:

    string str_var;

    string str_var = "initial value";

Of course, we can have string constants, too:

    const string ProgTitle = "The Name Game";

There are many other ways to initialize string variables/constants. Be sure to see the pertinent example for more information.

With class You Get Function

As we've seen from both cin and cout, classes provide functions for their objects to use. The string class is no different. It gives us many functions for normal use and some for enhanced/advanced use.

To call such functions, simply use the name of your string variable or constant object, a dot, and the function call following. For instance, if we wanted to prepare a greeting for our user, we could use the insert() function:

    string name, greeting = "Hello , welcome to the program!";

    cout << "What is your name (first only)?  ";
    cin >> name;

    greeting.insert(6, name);    // insert their name before the ,

    cout << greeting << endl;

If the user said their name was "Liselle", we would insert this before the ',' (which is in position 6 of the initial greeting — we count from 0, remember?).

So then the user would then see on the screen:

    Hello Liselle, welcome to the program!
    _

In the table below of string class functions you can use, s is a string object or literal, p is a position within a string (string::size_type — for more on size_type see the earlier notes), and n is a number of characters (string::size_type). Also, 'calling string' refers to the string object which is on the left of the dot (.) operator in the call to the function.

For instance, in the example call to insert we saw above:

    greeting.insert(6, name);    // insert their name before the ,

greeting is the 'calling string'.

Among the many string class functions available are:

Generalized Head Description
insert(p,s) insert s into 'calling string' to be at position p (that is, in front of what is currently at position p)
erase(p,n) erases n characters from the 'calling string' beginning at (and including!) position p.
erase(p) erases from position p to the end of the 'calling string'.
replace(p,n,s) replaces the n characters of the 'calling string' starting at position p with s.
assign(s,p,n) assigns the 'calling string' to be a copy of the n characters of the string s starting from position p. (Assign here is just like the assignment operator (=) in that it will overwrite the current contents of the calling string object with the sequence of characters from the 'argument string. The original content of the calling object is lost.)

If n is string::npos, the rest of s from p is copied.
substr(p,n) return a copy of the n characters of the 'calling string' starting from position p as a separate string object.

If n is string::npos, the remainder of the 'calling string' starting at p is copied.
substr(p ) return a copy of the character of the 'calling string' at position p and all that follow it as a separate string object.
compare(s) compares the 'calling string' (let's call this c) to the string s. If c < s, a negative integer is returned (it will be a small value). If c == s, zero (0) is returned. if c > s, a positive integer is returned (also a small value).

Why not just use the comparison operators instead? Many programmers like the compactness of this style so that they simply remember a single interface and it does all the comparisons at once. It is also more economical if we are checking several comparisons between the same two strings since we can store the result and then simply look at that variable rather than having to re-compare the strings again.

For example:

    short comp = s1.compare(s2);
    if (comp < 0)
    {
        // s1 is < s2
    }
    else if (comp > 0)
    {
        // s1 is > s2
    }
    else
    {
        // s1 is == s2
    }
For more on this and making it case insensitive, see the earlier notes.
find(s) locates the first occurance of the [sub-]string s within the 'calling string' and returns its position

If s cannot be found, returns string::npos. This constant defined inside the string class is guaranteed to be greater than or equal to the length of any string the system can hold. So you can check for success of the search with either:

    string::size_type pos;
    string str;

    pos = str.find("stuff");
    if ( pos != string::npos )
    {
        // str.substr(pos, 5) == "stuff"
    }
    else
    {
        // there is no copy of "stuff" in the variable str
    }
or:

    string::size_type pos;
    string str;

    pos = str.find("stuff");
    if ( pos < str.length() )
    {
        // str.substr(pos, 5) == "stuff"
    }
    else
    {
        // there is no copy of "stuff" in the variable str
    }
find(s,p) as find(s), but starts looking at position p of the 'calling string'
rfind(s) as find(s), but starts looking at the end of the 'calling string' and looks toward the beginning
rfind(s,p) as rfind(s), but starts looking at position p of the 'calling string'
find_first_of(s) locates the first occurance of any character in s in the 'calling string'
find_first_of(s,p) as find_first_of(s), but starts looking at position p of the 'calling string'
find_last_of(s) as find_first_of(s), but starts looking at the end of the 'calling string' and looks toward the beginning
find_last_of(s,p) as find_last_of(s), but starts looking at position p of the 'calling string'
find_first_not_of(s) locates the first character of the 'calling string' that is *NOT* in the string s
find_first_not_of(s,p) as find_first_not_of(s), but starts looking from position p of the 'calling string'
find_last_not_of(s) as find_first_not_of(s), but starts looking from the end of the 'calling string' and looks toward the beginning
find_last_not_of(s,p) as find_last_not_of(s), but starts looking from position p of the 'calling string'
length() returns the number of characters in the 'calling string'
size() as length()
empty() returns true if the 'calling string' has no characters in it (false otherwise)
clear() makes the 'calling string' empty (erases all characters in the string)

For More

Don't forget to look through all the string examples online.

My favorites are the sentence cleaner and the text reversal.


NOTE: More to come...