Learn C++ · lesson 6 of 61 · about 6 minutes
std::string Basics
Put your hero's name up in lights: join strings with +, measure them with size(), and read characters by index.
What you'll learn
- Join strings with + and +=
- Measure with size()
- Read and change characters by index
Names in lights
Your adventure should greet the hero with a banner: their name between stars, and a line of = exactly as long underneath. Every player types a different name, so the program has to measure the text itself.
std::string is text that knows its own length:
a + bjoins two strings, ands += "!"adds to the ends.size()is the number of characterss[0]is the first character: indexes start at 0, and a single character is written in single quotes, like'A'==compares the textstd::string(5, '=')makes a string of five=
A banner that fits any name
#include <iostream>
#include <string>
int main() {
std::string hero = "Ada";
hero += " the Brave";
std::string banner = "*** " + hero + " ***";
std::cout << banner << "\n";
std::cout << std::string(banner.size(), '=') << "\n";
std::cout << banner.size() << " characters\n";
}Output
*** Ada the Brave ***
=====================
21 charactersReading and changing single characters
#include <iostream>
#include <string>
int main() {
std::string word = "cave";
std::cout << word[0] << word[word.size() - 1] << "\n";
word[0] = 'g';
std::cout << word << "\n";
std::cout << std::boolalpha << (word == "gave") << "\n";
}Output
ce
gave
trueTip
"Open " + "sesame" doesn't compile: text in double quotes on its own isn't a std::string, and two of them can't be added. At least one side of + has to be a std::string.
Now try it yourself
This lesson is free in Codiqo, with 9 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.