Operators and Strings: std::string, string_view and std::format
Learn arithmetic and comparison operators, the std::string class, string_view, and the C++20 std::format function, with real output checked against Python.
In this lesson you will
- Use operators correctly
- Work with std::string
- Use string_view to avoid copies
- Format text with std::format
About 28 minutes
Station names and readings in text
Elena labels each reading with a station name and wants tidy output: names in columns, numbers with two decimals. In C++ the class std::string holds text, grows automatically and cleans up after itself, which is a great improvement over the character arrays that C uses. Since C++20 the header provides std::format, which builds text from a format string with placeholders, in the style that Python and C# programmers already know.
A std::string has methods such as size, substr, find, replace, append and compare, and the operator + joins strings. Strings are mutable in C++, unlike in Java and C#, so s += “x” changes s in place. A std::string_view is a lightweight window onto characters owned by someone else: it holds a pointer and a length and never copies, so it is ideal for function parameters that only read text. The price is that a view must not outlive the string that it looks at. Format strings use braces, with a colon introducing a specification: {:.2f} means two decimals, {:>8} right-aligns in a width of 8, {:<8} left-aligns, and {:08.3f} pads with zeros.
| Need | Code |
|---|---|
| Length | s.size() |
| Find | s.find(“abc”) returns an index or npos |
| Part of a string | s.substr(start, length) |
| Replace in place | s.replace(pos, len, text) |
| Read-only parameter | std::string_view |
| Format | std::format(“{:.2f}”, x) |
#include <cctype>
#include <format>
#include <iostream>
#include <string>
#include <string_view>
std::size_t count_char(std::string_view text, char c) {
std::size_t n = 0;
for (char ch : text) if (ch == c) ++n;
return n;
}
int main() {
std::string station = "Roof Station";
std::cout << station << " has " << station.size() << " characters\n";
std::string upper = station;
for (char& c : upper) c = static_cast<char>(std::toupper(static_cast<unsigned char>(c)));
std::cout << upper << " | original unchanged: " << station << "\n";
std::cout << "substr(0, 4) = " << station.substr(0, 4) << ", find(\"Station\") = " << station.find("Station") << ", find(\"x\") is npos: " << (station.find("x") == std::string::npos) << "\n";
station.replace(0, 4, "Garden");
station += " #1";
std::cout << "after replace and append: " << station << "\n";
std::cout << "letter t appears " << count_char("temperature at ten", 't') << " times (string_view, no copy)\n";
double t = 21.456, h = 63.0;
std::cout << std::format("[{:<10}] [{:>8.2f}] [{:08.3f}] [{:5d}] [{:x}]\n", "temp", t, t, 42, 255);
std::cout << std::format("{} is {}% humid, {:.1f} C", station, h, t) << "\n";
std::cout << "100 / 3 = " << 100 / 3 << ", 100 % 3 = " << 100 % 3 << ", 100.0 / 3 = " << std::format("{:.4f}", 100.0 / 3) << "\n";
std::cout << "compare: " << (std::string("abc") == "abc") << " " << (std::string("abc") < std::string("abd")) << "\n";
}
Roof Station has 12 characters
ROOF STATION | original unchanged: Roof Station
substr(0, 4) = Roof, find("Station") = 5, find("x") is npos: 1
after replace and append: Garden Station #1
letter t appears 4 times (string_view, no copy)
[temp ] [ 21.46] [0021.456] [ 42] [ff]
Garden Station #1 is 63% humid, 21.5 C
100 / 3 = 33, 100 % 3 = 1, 100.0 / 3 = 33.3333
compare: 1 1
The station name has 12 characters, and the loop that made the upper-case copy left the original alone, because we copied the string first. The substring of length 4 is “Roof” and the word “Station” starts at index 5, counting from zero, while a missing word makes find return the special value npos. Strings are mutable, so replace and += changed the string in place, giving “Garden Station #1”.
The function count_char takes a string_view, so it works on a string literal without copying a single character, and it counted 4 letters t. The formatted line shows the specifications at work: [temp ] [ 21.46] [0021.456] [ 42] [ff]. The text is left-aligned in ten columns, the number 21.456 is rounded to 21.46 in a width of eight, padded with zeros as 0021.456, and 255 in hexadecimal is ff. The second formatted line puts the station name and the numbers into a sentence. Integer division gave 33 and the decimal version 33.3333.
Check by hand: “Roof Station” is 4 + 1 + 7 = 12 characters, and “Station” starts after “Roof ” at index 5. 21.456 rounded to two decimals is 21.46. The word “temperature at ten” has t at the start of “temperature”, at the end of “temperature”, in “at” and at the start of “ten”, which is four. Python’s format specifications give the same strings, because std::format follows the same mini-language.
If you keep a view of a temporary string that is destroyed, the view points at freed memory. Use views for parameters and short-lived work, and std::string for storage.
They manage memory for you and make formatting safe. Old-style char arrays and printf bring buffer overflows and type mistakes.
Every program in this lesson was compiled with GCC 13 using -std=c++20 -Wall -Wextra and run while the course was written. C++ has a new standard every three years and compilers differ in what they support, so check your compiler’s documentation and cppreference.com for the current state. std::format needs a standard library that supports C++20, such as GCC 13.
Practice
Write a function that takes a string_view and returns the number of words. Format a table of three stations with names left-aligned and temperatures right-aligned with one decimal. Reverse a string with std::reverse from .
Check what you learned
Five quick questions. Pick an answer and you will see straight away whether it is right and why.
What does std::string::find return when nothing is found?
- -1 as an int
- 0
- An exception
- std::string::npos
A special large value.
Why take a string_view parameter?
- It changes the text
- It is required
- It reads text without copying
- It is faster to type
Do not store it past the owner’s life.
What does {:>8.2f} do in std::format?
- Left-aligns text
- Prints hex
- Right-aligns a number with two decimals in width 8
- Prints twice
The specification mini-language.
Are C++ strings mutable?
- No
- Yes
- Only literals
- Only in C
replace and += change them in place.
What is 100 / 3 with two ints?
- 33.33
- 33
- 34
- 3
Integer division truncates.
Summary
- std::string holds mutable text and manages its own memory.
- string_view reads text without copying.
- std::format builds text with placeholders and specifications.
- Integer division truncates.
Questions
What is a C string?
A char array ended by a zero byte, from C. It is still used in old code. Prefer std::string in new code.
Is std::format available everywhere?
It is part of C++20, and compilers added support at different times. Check your compiler. The older iostreams and the fmt library offer similar features.
What does std::toupper need the unsigned char cast for?
Passing a negative char value is undefined behaviour, so cast to unsigned char first.
