Although we have worked with string literals enclosed in quotes like "Hello world", we have yet to store or manipulate those strings. To do so, we need to create a variable of type string. To work with the string data type, you need to include the <string> library. Then you can create and assign values to variable with type string in the usual ways:
The full formal name of string is std::string. Like with std::cout or std::endl, you can either use that full name or add using namespace std; to your file, in which case the compiler will assume that string really means std::string.
Strings have a maximum length that depends on the platform (usually billions of characters). And they can be can be just 1 character long, or even 0 characters. Unlike numeric types, if you fail to initialize a string, you can count on it being empty instead of having a random value:
string empty = "";
string alsoEmpty; // we know this string holds ""
string single = "a";
Note9.3.2.
If you are already including iostream, you may get away with not explicitly including string. In some environments, iostream will include string for you. But it is best to explicitly include string if your code relies on it.
The term object in programming refers to a code entity that bundles some data together with functions that operate on that data. strings in C++ are objects. And they are one of the first kind of objects we will deal extensively with. (cout and cin are objects, but we havenβt had to know that to use them.)
We will lean much more about objects in a later chapter ChapterΒ 9. For now, the important thing to know is that the way you interact with an object is to call functions βon itβ. Which looks different than calling a function and passing it all of the data. To call a function on an object we use the syntax:
This syntax is called βdot notation,β because the dot (period) separates the name of the object from the name of the function. For example, to find the size (number of characters) of a string called fruit, we can use its size function by saying fruit.size():
Functions that are a part of an object are often referred to as methods or member functions. You should think of fruit.size() as saying βcall the size method of fruitβ or βask fruit to run its size methodβ.
When using methods, we always have to specify which object is going to be running the method using dot notation. Which string exactly are we asking about its size? Trying to use size() without someStringName. before it would be a syntax error:
It is important to recognize that a string, even with only one character, is different than a char variable. A char is just a number that represents a character. A string is a list of 0 or more characters and has built in functions. Even if a string currently only has one character, it may later be modified to have more.