Strings
In this lesson, you will learn how to use variables that store text. As humans, text is the primary medium through which we interact with computer programs. Learning basic text storage and manipulation is crucial to making functional applications that people can and want to use.
Motivationโ
The world runs on text. Variables that can store text turn out to quite useful because of this. Consider a program which reads the user's name, then greets them with the number of characters in their name.
#include <iostream>
#include <string>
int main()
{
std::string name;
std::cout << "Enter your name: ";
std::cin >> name;
std::cout << "Welcome, " << name << "!\n";
std::cout << "Your name has " << name.size() << " characters.\n";
}
A type for storing textโ
In previous lessons, we talked about different types of variables, though we focused on those
that store numbers. We mentioned the char
type, which stores
a single character.
In programming, text is a series of characters โ โ known as a string.
C++ provides us with the type std::string
to store and manipulate strings.
You must include the string
header to use std::string
in your code,
in the same way as we did earlier with iostream
:
#include <string>
The std::string
type is used just like any other.
Here, we make two variables โ one of type int
, and another of type std::string
:
int number;
std::string text;
Initializationโ
Assigning the initial value is the same as for variables of other types, but note that text is specified between double quotes, not single quotes:
std::string welcome = "Hello, World!";
std::cout << welcome;
If no value is given, the string will be empty. The text is length 0, and printing it to the console will show nothing.
String operationsโ
User interactionโ
We can display the strings using std::cout
and load them using std::cin
.
#include <iostream>
#include <string>
int main()
{
std::string name;
std::cout << "Enter your name: ";
std::cin >> name;
std::cout << "Welcome, " << name << "!\n";
}
Note that std::cin
takes the input text until it encounters the first whitespace character, such as a space, tab, or newline.
Because of this, if we enter our first and last name, only the first name will go into the name
variable.
To get the whole line of text, you can use std::getline
:
std::string full_name;
std::getline(std::cin, full_name);
std::getline
is a function that takes two arguments - an input stream to read the line from, and an std::string
variable to store the line in.
This example shows how you can use this function to read a line from std::cin
.
So, this function is "called" by putting the name of the function std::getline
, then parentheses (...)
, and inside the parentheses the
arguments we want to provide std::cin, full_name
.
Combining Stringsโ
The +
and +=
operators can be used to concatenate and append strings together.
Consider the following abridged example with an input of Dwayne Johnson
:
std::string first_name;
std::string last_name;
std::cin >> first_name;
std::cin >> last_name;
// Concatenation
std::string coolName = first_name + " \"The Rock\" " + last_name;
std::cout << "Your cool name is:\n" << coolName << "\n\n";
// Appending
coolName += " Mk II";
std::cout << "Your new name is:\n" << coolName;
Your cool name is:
Dwayne "The Rock" Johnson
Your new name is:
Dwayne "The Rock" Johnson Mk II
Notice how coolName
is the result of concatenating three strings - first_name
, "The Rock"
, and last_name
.
Then, see how we modify coolName
by appending " Mk II"
to it.
Reading the lengthโ
To check how many characters are in a string we use the so-called method size
.
We'll talk more about functions and methods later in the course, as they are a very important concept.
Let's see how to use the size
method in practice. Consider the following example with an input of Johnny
:
#include <iostream>
#include <string>
int main()
{
std::string name;
std::cout << "Enter your name: ";
std::cin >> name;
std::cout << "\nWelcome, " << name << "!\n";
std::cout << "Your name has " << name.size() << " characters.\n";
}
Welcome, Johnny!
Your name has 6 characters.
We call the size
method by doing name.size()
. The .
indicates that we are accessing something on
our name
variable. size
is the name of the method we are accessing. The ()
calls the size
method.
This gives back to us the total number of characters in the string. These terms aren't crucial to remember now,
but you will see them later in the Functions and Methods lessons; just remember how to use it.
Just to reiterate, we specify the variable (name
), then we write size
after the period and then empty round brackets:
name.size()
Conversions between numbers and stringsโ
Numbers and strings cannot be freely converted to each other without a specialized function that does it for us. This is because number types and string types in C++ are disinctly different, and not generally compatible. While it may be annoying, this is actually very important for making bug-free code.
53
"53"
The first value is the arithmetic number 53
. It represents a value that we can perform mathematical operations on.
The second value is text consisting of the characters '5'
and '3'
. We can't perform math on strings; rather,
the string operations we can perform are concatenations.
These are the incorrect ways of trying to convert between strings and numbers, all causing compilation errors:
- โ Incorrect
- โ Incorrect
- โ Incorrect
- โ Incorrect
int number = 53;
std::string str = number; // Error
std::string str = 53; // Error
std::string str = "53";
int number = str; // Error
int number = "53"; // Error
To convert from a number type (like int
or float
) to string, we need to use the std::to_string
function.
int number = 53;
std::string number_in_str = std::to_string(number);
In the same way, if we have a number stored inside a string, we can
convert it to an int
with std::stoi
(string to int) and
to float
type with std::stof
(string to float):
- ๐ต std::stoi
- ๐ฃ std::stof
std::string number_in_str = "53";
int number = std::stoi(number_in_str);
std::string number_in_str = "53.5"; // do not put `f` at the end in the text
float number = std::stof(number_in_str);
Summaryโ
In this lesson, we learned about the std::string
type, which is a type that represents a sequence of characters.
Head over to sublessons to find out more about strings: