C++ STL string class
The C++ standard template library (STL) provides us
with many common containers that we can use in our programs.
One common container provided by the C++ library is a string.
The string container is used to store a sequence of characters, and
generally replaces the troublesome
null-terminated character arrays used in C. Note that there are
programming situations when a
character array is required. C++ strings may be converted to
null-terminated C-style char arrays when necessary. For the moment, think
of C++ strings as a new data type with a slightly strange syntax.
To use strings, you must include its associated
header file --- #include <string>
What are some common operations you would expect a string class to support?
- Support to initialize a string object with the empty string
The code string firstName;
constructs a variable called "firstName" as a string
which is initialized to the empty string (no characters).
- Support to initialize a string with a sequence of characters
The code string middleName ("bob");
or equivalently string middleName = "bob";
constructs a variable called "middleName" as a string
initialized to the sequence of characters "bob".
- Support to initialize a string as a copy of an existing string
The code string lastName (middleName);
constructs a variable called "lastName" as a string
initialized as a copy of the existing string
above called "middleName"
- Support to copy one string to another
With primitive types such as int, float and char, we copy the
contents of one existing variable into another using assignment
with code like x = y;
Very often (almost always) it is possible to copy one existing variable
into another existing variable of the same type also by
using the standard assignment statement. Using the string
constructed above,
the statement firstName = lastName;
copies the contents of "lastName" into the string "firstName".
- Support to access the individual characters of the string
We can access the individual characters of a string in a manner similar to
the C-style character array using square brackets ( [ ] )
char char2;
char2 = firstName[1];
assigns (copies) the second character of the string object "firstName" to the
character variable char2.
Similarly,
firstName[0] = 'x';
changes the first character of firstName to 'x'
- Support to compare two strings for equality
We can compare two integers (or other primitive type)
using the equality operator "==" as the following code illustrates
if (x == y)
{
// do something
}
The same thing is true of strings and many other classes.
The equality operator for
string compares two strings and returns true if the are equal.
if (firstName == lastName)
{
// do something;
}
Other comparators such as <, >, and != can also be used with strings
and produce the expected, intuitive results.
- Support of string concatenation
We can concatenate (append one string to the end of another) two strings together
using "string addition".
string hello = "Hello";
string world( "World" );
string result = hello + world + "!";
cout << result;
prints HelloWorld!
- Support to know how many characters are contained in the string
We can ask a string how many characters it contains by
using the string's size( ) operation.
Note the syntax that is similar to that used for structures in C.
int nrChars;
nrChars = firstName.size( );
This syntax (the dot and parentheses) indicate that we are requesting that the
string "firstName" perform the size( ) operation.
We know from the string documentation that the size( )
operation requires no parameters and returns an integer value.
- Support to know if the string is empty.
A similar operation provided by strings is the boolean
empty( ) operation.
From the string documentation we know that empty( )
takes no parameters and returns a boolean
-- true if the string is empty, false if not empty.
We can now write code such as
if ( ! lastName.empty( ) )
// do something if not empty.
Of course, we could have chosen to write
if ( lastName.size( ) != 0 )
- Treat the C++ string as a C-style string.
If we desire to treat the C++ string as a C-style string
(perhaps to pass to some function), we ask the string
to perform the c_str() operation.
// given the declarations
string s1 = "bob";
char s2[] = "This is a C-style string";
// this code copies s1 onto s2 using strcpy()
strcpy (s2, s1.c_str());
- Access a substring
Sometimes it's useful to be able to access just part (consecutive characters) of the
string (a "substring"). The string operation substr(int index, int length )
gives us that access. Consider the following code.
string sentence = "The quick brown fox jumped over the lazy dog.";
// these statements print
// The fox
cout << sentence.substr( 0, 4);
cout << sentence.substr( 16, 3) << endl;
Other operations are possible with strings and there are
several common functions that work with string. See the
C++ STL
strings reference page and section 9.3 of the text for more details.
I/O with strings
You can output strings using operator << and cout, just like you
do with other basic data types.
string firstName = "Mary";
string lastName = "Jones";
cout << lastName << "," << firstName << endl;
outputs Jones,Mary
You can use the input operator >> and cin to input strings from
the user. However, remember that the >> operator ignores leading whitespace
and stops reading when it sees the next whitespace. This technique is
used for reading "words". Consider this code
string firstName, lastName;
cin >> firstName;
cin >> lastName
If the user types Mary Jones is cool.
Then firstName contains "Mary" and lastName contains "Jones".
The words is cool are waiting to be read.
To read a "sentence" (multiple words separated by blanks), use the function
getline( ) as in the code below.
string sentence;
getline (cin, sentence);
This time if the user types Mary Jones is cool.
Then the entire line of text is read and
sentence contains "Mary Jones is cool.".
The difference between using >> and getline( ) is illustrated in
the example code.
Analysis
- What are some advantages of C++ strings?
- What are some disadvantages of C++ strings?