Strings in C++: std::string, string_view and parsing text safely
How to work with text in modern C++: std::string vs std::string_view, splitting and trimming, converting numbers strictly, UTF-8 basics, and parsers built as state machines.
Most real programs start by reading text: a file, a log line, a form field. Parsing it strictly is where many bugs and security issues start, so it's worth doing well.
std::string and std::string_view
std::string owns its characters. std::string_view is a cheap, read-only window onto characters
owned by someone else.
std::optional<Reading> parse_reading(std::string_view line); // reads, doesn't keepA string_view parameter accepts std::string, literals and substrings without copying. The one
rule: never keep a string_view longer than the text it points to.
Splitting and trimming
std::string_view trim(std::string_view text) {
const auto first = text.find_first_not_of(" \t");
if (first == std::string_view::npos) return {};
const auto last = text.find_last_not_of(" \t");
return text.substr(first, last - first + 1);
}
const auto comma = line.find(',');
if (comma == std::string_view::npos) return std::nullopt; // no comma: reject
const auto sensor = trim(line.substr(0, comma));
const auto value = trim(line.substr(comma + 1));All of this is copy-free: substr on a string_view returns another view.
Converting numbers strictly
"5abc" must not become 5. Check that the whole text was consumed:
#include <charconv>
std::optional<int> parse_int(std::string_view text) {
int value = 0;
const auto [end, error] = std::from_chars(text.data(), text.data() + text.size(), value);
if (error != std::errc{} || end != text.data() + text.size()) return std::nullopt;
return value;
}std::from_chars doesn't skip spaces, doesn't depend on the locale and doesn't throw.
Characters and UTF-8
A char is a byte, and UTF-8 uses several bytes for characters like ä or emoji. Two practical
rules:
- To count characters, count bytes that are not continuation bytes:
(static_cast<unsigned char>(c) & 0xC0) != 0x80. - Always cast to
unsigned charbefore callingstd::isalphaand friends; negative values are undefined behaviour.
Bigger formats: state machines and recursive descent
For formats with quoting, like CSV, a small state machine (in a field, in quotes, just after a quote) handles every case clearly; build one in the Market Square sales report. For nested formats like JSON or formulas, recursive descent (one function per grammar rule) is the standard technique; see the Configo JSON parser.
Whatever the format, report where the input went wrong. "Invalid input" is useless in a 2,000-line file. How to report failure is covered in error handling in C++.
Questions and answers
- When should a function take std::string_view?
- When it only reads the text and doesn't keep it. A string_view avoids copies and accepts std::string, string literals and substrings alike. Don't store a string_view whose source may go away.
- Why not use std::stoi to parse numbers?
- std::stoi accepts leading spaces and a sign, ignores trailing garbage ('12abc' gives 12) and throws on failure. For strict parsing, check the characters yourself or use std::from_chars and verify it consumed everything.
Practise it in a project
These projects put this guide to work, with tickets, tests and code review.
Frostline Cold Storage
Sensor readings summary for Frostline
Turn the raw export of Frostline's freezer sensors into a summary per freezer, and flag readings outside the safe range.
- parsing text
- structs
- std::map
- floating point
Market Square
Weekly sales report for Market Square
Parse Market Square's sales export, quotes and all, and turn it into revenue per category without letting one bad row spoil the report.
- state machines
- CSV quoting
- error reporting
- aggregation
Tracehound
Log analysis for Tracehound
Parse structured log lines, quoted values and all, then compute error rates and p95 latencies so on-call engineers find the slow endpoint in seconds.
- tokenising
- key-value parsing
- percentiles
- aggregation
Configo
A JSON parser for Configo
Write the strict, dependency-free JSON parser at the heart of Configo: exact error positions, Unicode escapes, depth limits, compact output and path lookups.
- recursive descent
- recursive data types
- Unicode and UTF-8
- defensive parsing