C++ Strings
A string is a piece of text stored in a std::string variable. A string can hold letters, spaces, and other characters.
A string variable prints
The variable holds one piece of text. The print line shows the text it holds.
#include <iostream>
#include <string>
int main() {
std::string greeting = "Hello";
std::cout << greeting << std::endl;
return 0;
}Joining two strings
The + sign joins the two strings into one text. The joined text prints as a single line.
#include <iostream>
#include <string>
int main() {
std::string first = "Hello, ";
std::string name = "Hana";
std::cout << first + name << std::endl;
return 0;
}One character by index
An index gives one character from a string. Index 1 of Hello gives the single letter e.
#include <iostream>
#include <string>
int main() {
std::string word = "Hello";
std::cout << word[1] << std::endl;
return 0;
}A string with spaces
This string holds a first name and a last name. The space between the names is part of the text.
#include <iostream>
#include <string>
int main() {
std::string name = "Hana Kim";
std::cout << name << std::endl;
return 0;
}Comparing two strings
The == sign compares the text in the variable with the text in quotes. The std::boolalpha setting makes the result print as the word true.
#include <iostream>
#include <string>
int main() {
std::string word = "hello";
std::cout << std::boolalpha;
std::cout << (word == "hello") << std::endl;
return 0;
}Example
#include <iostream>
#include <string>
int main() {
std::string first = "Hana";
std::string last = "Kim";
std::string full = first + " " + last;
std::cout << full << std::endl;
std::cout << "Hello, " << full << std::endl;
return 0;
}Key points
- The <string> header gives a program the std::string type.
- A std::string variable stores one piece of text.
- Use + to join two strings into one longer string.
- An index in square brackets reads one character from a string.
- The first character of a string sits at index 0.
- A string can hold spaces between words.
- The == sign compares two strings by their text.
In this example, first holds Hana and last holds Kim. The + signs join the names with a space between them. The first line prints the full name. The second line prints a greeting that uses the full name.
Note
Text in a string sits inside double quotes.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
A variable named word holds "Hello". What does word[1] give?