Strings
-
ANSI C++ can handle sequences of characters called strings.
-
Strings behave like (but are actually not) a build-in data type such as int or double. They are actually objects of the C++ standard string class (more on that a couple of months from now).
-
The syntax for declaring an object of type string is:
string stringName;
-
You must include the header file <string> in order to use the strings.
-
The string class overloads the = operator to copy one string of any length into another. (More about overloading operators in CS1124.) For example:
stringName = "The 3 rings associated with marriage are: engagement ring, wedding ring, and suffering."
-
cin and cout, together with the operators >> and <<, are overloaded to perform input and output of strings. cin >> ignores leading whitespaces and reads up to the next whitespace (but does not consume that whitespace). Reading strings this way actually reads words (a sequence of non-whitespace characters) and not lines.
-
To illustrate the usage of some of the features about the string class,
consider the following code:
#include <iostream>
#include <string>
using namespace std;
int main( )
{
string compoundWord, word1, word2;
cout << "Enter two separate words: ";
cin >> word1 >> word2;
compoundWord = word1 + word2;
cout << "These words joined together form the string: " << compoundWord
<< endl;
return 0;
}
Two words entered from the keyboard are stored separately in strings word1 and word2.
They are then concatenated (joined together) by the overloaded operator "+", and assigned to the string compoundWord. The result is then output to the screen.