When discussing common data types we briefly mentioned the type string. What sets this data type apart from the other common types (e.g. int, double, char) is that the string type is not a part of the language's core (i.e, not a "primitive" data type).
Instead it is an example of a class which happens to have been defined in one of the standard C++ libraries. Therefore, when we wish to use it we must preface our code with the directive:
#include <string>We will look at this class as our first example of object-oriented programming.
Let me stress that these notes are meant as a very coarse outline; please refer to the text for more explanation.
A string object has a set of attributes or data members (for representing the state of the object), yet it also supports a set of actions or member functions. We will look at several examples of the actions supported by this class. For each, we will focus on the transfer of information which takes places in such a method call, namely in the parameters sent to the method, and in the return value sent back as a result.
int size()
returns the total length of the string
char at(int index)
returns the single character at the given index
substr(int start, int length)
returns a substring starting at index 'start' and going for up
to length characters.
int find(string pattern)
int find(string pattern, int start)
returns the smallest index >= start, if one exists, such that
the given pattern can be found as a substring in the original
string starting at such index.
Several operators have been defined to deal with string data as well, most notably:
The << operator for printing a string
cout << firstName;
The >> operator for inputting a string
cin >> lastName;
The + operator for concatenating two or more strings
fullName = firstName + " " + lastName;
A further note about reading strings from input. When using the >> operator, such as in
cin >> name;any form of whitespace in the input is used as a delimiter. Thus if the user types in
Saint Louis Universityin the above example, the variable name will be set equal to the string "Saint" as opposed to
getline(istream streamName, string result)
getline(istream streamName, string result, char delim)