Strings and regular expressions

std::string methods, building text with std::ostringstream and std::format, splitting, and <regex>.

Runs in Zerethon IDE · C++ (GCC 14) Official C++ documentation ↗
main.cpp
#include <algorithm>
#include <cctype>
#include <iostream>
#include <regex>
#include <sstream>
#include <string>

int main() {
    std::string name = "Ada Lovelace";
    std::cout << name.size() << ' ' << name.substr(0, 3) << ' ' << name.find("Love") << '\n';

    std::string upper = name;
    std::transform(upper.begin(), upper.end(), upper.begin(), [](unsigned char c) { return std::toupper(c); });
    std::cout << upper << '\n';

    std::stringstream parts("a,b,c");
    for (std::string part; std::getline(parts, part, ',');) std::cout << '[' << part << ']';
    std::cout << '\n';

    std::smatch m;
    std::string text = "order 7 pending";
    if (std::regex_search(text, m, std::regex(R"(order (\d+))"))) std::cout << m[1] << '\n';
    std::cout << std::regex_replace("a1b22c", std::regex(R"(\d+)"), "#") << '\n';
}

Output

12 Ada 4
ADA LOVELACE
[a][b][c]
7
a#b#c
main.cpp
#include <format>
#include <iostream>

int main() {
    std::cout << std::format("{:.2f}|{:>5}|{:03}|{}", 3.14159, 42, 7, "text") << '\n';
}

Output

3.14|   42|007|text
std::format (C++20) formats like Python's str.format.
  • find returns std::string::npos when the text is not there.
  • Raw strings R"(…)" keep backslashes as written — convenient for regular expressions.
  • A file that includes several heavy headers (for example <regex> and <format> together) can fail to compile with File size limit exceeded: see “Common errors”.