Skip to content

Text Processing: Strings, Streams and Regular Expressions

Beginning of the lesson

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::string member functions,
  • parse whitespace- and delimiter-separated fields with std::istringstream and build output with std::ostringstream,
  • write std::regex patterns and choose between regex_match, regex_search and regex_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 constant std::string::npos if it is not present. Always compare against npos - never against -1.
  • s.substr(pos, len) returns a new string copied from pos; if you omit len it runs to the end.
  • s.replace(pos, len, repl), s.insert(pos, txt), s.erase(pos, len) and s += "..." edit in place.
  • s.size() (same as length()), s.empty(), s[i] for unchecked access, and s.at(i) for bounds-checked access that throws std::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.

Continue this lesson on YourAIZone

The full lesson has the complete explanation, worked examples, common mistakes, tests with instant checking and an AI tutor. Start right away as a guest, or create an account to keep your progress.

In the full lesson

  • The complete explanation
  • Worked examples
  • Common mistakes and how to avoid them
  • Test questions: 15
  • AI tutor that answers questions about the topic
  • Progress tracking for students, parents and teachers