C++ · Module 6 · Lesson 51 min read

Strings in Depth & string_view

Numbers ↔ strings

FunctionExample
std::to_string(x)to_string(42) → "42"
std::stoi(s)"42" → 42 (throws on bad input)
std::stol, std::stolllong, long long
std::stod(s)"3.5" → 3.5
std::from_chars / std::to_charsfast, no exceptions (C++17, <charconv>)
std::format("{:.2f}", x)formatted text (C++20)

stoi throws std::invalid_argument for "abc" and std::out_of_range for huge numbers. It accepts "12abc" (returns 12) — pass a std::size_t* to see how many characters were used.

Changing case (<cctype>)

arduino
for (char& c : s) c = static_cast<char>(std::toupper(static_cast<unsigned char>(c)));

Cast to unsigned char first — passing negative chars to toupper is undefined behaviour.

Splitting a string

Use std::istringstream (<sstream>):

c
std::istringstream in("10,20,30");
std::string part;
while (std::getline(in, part, ',')) { ... }

Trimming whitespace

find_first_not_of(" \t\n") and find_last_not_of(...) with substr.

std::string_view (C++17, <string_view>) ✅

A non-owning view: just a pointer + length.

arduino
void print(std::string_view text);   // accepts std::string, "literals", and substrings cheaply
  • Copying it is free; substr() on a view creates no new string
  • ⚠️ It doesn't own the data: never return a string_view to a local string or a temporary
  • Not guaranteed null-terminated — don't pass .data() to C functions expecting \0

Other handy members

s.rfind(), s.find_first_of("aeiou"), s.compare(), s.c_str() (for C APIs), std::reverse(s.begin(), s.end()) (<algorithm>)

Raw string literals

R"(C:\Users\asha\notes.txt)" — no escaping needed for backslashes and quotes.

Example

C++
#include <algorithm>
#include <cctype>
#include <iostream>
#include <sstream>
#include <stdexcept>
#include <string>
#include <string_view>
#include <vector>

std::string to_upper(std::string s) {
    for (char& c : s) c = static_cast<char>(std::toupper(static_cast<unsigned char>(c)));
    return s;
}

std::string_view trim(std::string_view s) {
    auto first = s.find_first_not_of(" \t\n");
    if (first == std::string_view::npos) return {};
    auto last = s.find_last_not_of(" \t\n");
    return s.substr(first, last - first + 1);         // no copy: just a smaller view
}

std::vector<std::string> split(const std::string& text, char sep) {
    std::vector<std::string> parts;
    std::istringstream in(text);
    std::string part;
    while (std::getline(in, part, sep)) parts.push_back(part);
    return parts;
}

int main() {
    int year = std::stoi("2026");
    double price = std::stod("499.75");
    std::string label = "Year " + std::to_string(year + 1);
    std::cout << label << ", price + 0.25 = " << price + 0.25 << '\n';

    std::size_t used = 0;
    int partial = std::stoi("12abc", &used);
    std::cout << "stoi(\"12abc\") = " << partial << " (used " << used << " chars)\n";
    try {
        std::stoi("abc");
    } catch (const std::invalid_argument&) {
        std::cout << "stoi(\"abc\") threw invalid_argument\n";
    }

    std::cout << to_upper("budget buddy") << '\n';
    std::cout << "[" << trim("   hello world \n") << "]\n";

    double total = 0;
    for (const auto& item : split("850,1200,300,2200", ',')) total += std::stod(item);
    std::cout << "CSV total = " << total << '\n';

    std::string word = "racecar";
    std::string reversed(word.rbegin(), word.rend());
    std::cout << word << " is a palindrome? " << std::boolalpha << (word == reversed) << '\n';

    std::string path = R"(C:\Users\asha\notes.txt)";      // raw string: no escaping
    std::cout << "file name: " << path.substr(path.rfind('\\') + 1) << '\n';
    return 0;
}

/* Output:
Year 2027, price + 0.25 = 500
stoi("12abc") = 12 (used 2 chars)
stoi("abc") threw invalid_argument
BUDGET BUDDY
[hello world]
CSV total = 4550
racecar is a palindrome? true
file name: notes.txt
*/