Where the char represents a single character, a string represents a collection of them acting as a single entity. On the “old days” a string was an array of characters, however, now a days, we have our own data type for them.
string message = "Strings contain multiple characters.";
A string is not a primitive data type, but an included class that comes with C++. This means there are methods for the object that allow you to modify the string.
Common methods of a string include:
Name | Purpose |
---|---|
size() | Get the number of characters in the string. |
length() | Basically the same as size. |
at(index) | Get’s the character at a specific index. Index starts at 0, just like an array. |
Comparing Strings
You can use your comparison operators on two strings. They will return a 0 (false) or 1 (true) response.
Reading Strings
Reading a string is similar to any other data type.
string city;
cout << "Enter the city you live in: ";
cin >> city;
cout << "You entered: " << city << endl;
This example has a small problem, as the cin stops reading data as soon as it gets a white space character. So a city with a space in, will not be the entire string.
However, there is a getline()
that C++ provides that you can use.
string city;
cout << "Enter the city you live in: ";
getline( cin, city, '\n');
cout << "You entered: " << city << endl;
By default, the last parameter isn’t required, and the new line character (\n) is chosen by default.
The C++ String Data Type and Operations was originally found on Access 2 Learn