Text Processing: Strings, Streams and Regular Expressions
Slicing, parsing, building and validating text with the C++ standard library
Big Idea: Almost every real program eats text and produces text: config files, CSV rows, log lines, user input, network messages. C++ gives you three cooperating tools for this work.
std::string stores and edits the characters. std::stringstream turns text into typed values and back again. std::regex describes and matches patterns. Used together they let you split a line, extract a number, and confirm an email looks valid without ever touching a raw char* or a hand-written parser loop.
By the end you will be able to:
- search, slice, and rebuild text with
std::stringmember functions, - parse whitespace- and delimiter-separated fields with
std::istringstreamand build output withstd::ostringstream, - write
std::regexpatterns and choose betweenregex_match,regex_searchandregex_replace, - pull captured groups out of a match and validate real-world input safely.
1. std::string: search, slice, rebuild
You met std::string in the beginner course as "a container of characters". At this level it pays to know it as a genuine sequence with a rich, index-based API from the <string> header. Three operations do most of the day-to-day work: find, substr, and replace / append.
s.find("x")returns the index of the first occurrence, or the special constantstd::string::nposif it is not present. Always compare againstnpos- never against-1.s.substr(pos, len)returns a new string copied frompos; if you omitlenit runs to the end.s.replace(pos, len, repl),s.insert(pos, txt),s.erase(pos, len)ands += "..."edit in place.s.size()(same aslength()),s.empty(),s[i]for unchecked access, ands.at(i)for bounds-checked access that throwsstd::out_of_range.
std::string path = "report.final.csv";
std::size_t dot = path.rfind('.'); // search from the RIGHT
std::string ext = (dot == std::string::npos)
? ""
: path.substr(dot + 1); // "csv"
Notice rfind: it finds the last dot, which is exactly what you want for a file extension. The guard against npos is not optional - calling substr with a bad position throws.