Legacy C++ › 5. Exceptions, Strings and I/O
std::string
Construction, searching, modification and conversion.
beginner #string#std-string#find#substr#c_str#conversion
Explanation
std::string (header <string>) is a dynamic, resizable character sequence that manages its own memory. It replaces most uses of char[] and <cstring>.
Common operations:
| Task | Code |
|---|---|
| Length | s.size() / s.length() |
| Concatenate | a + b, s += "x", s.append("x") |
| Compare | ==, <, s.compare(t) |
| Substring | s.substr(pos, len) |
| Search | s.find("x") returns the index or std::string::npos |
| Modify | insert, erase, replace, push_back |
| To C string | s.c_str() (valid until s changes) |
Convert numbers with std::ostringstream / std::istringstream (C++03), or std::stoi / std::to_string (C++11).
Example
#include <iostream>
#include <sstream>
#include <string>
std::string trim(const std::string& s) {
std::string::size_type b = s.find_first_not_of(" \t\n");
if (b == std::string::npos) return "";
std::string::size_type e = s.find_last_not_of(" \t\n");
return s.substr(b, e - b + 1);
}
int main() {
std::string s = " Hello, World ";
s = trim(s);
std::cout << "[" << s << "] " << s.size() << "\n";
std::string::size_type pos = s.find("World");
if (pos != std::string::npos) s.replace(pos, 5, "C++");
std::cout << s << "\n"; // Hello, C++
std::string t = "abc";
t += 'd';
t.insert(0, "<");
t.append(">");
std::cout << t << " " << (t < "b") << "\n"; // <abcd> 1
std::ostringstream out; // number -> string (C++03)
out << 42 << ":" << 3.5;
std::cout << out.str() << "\n";
std::istringstream in("17 apples"); // string -> number
int n; std::string word;
in >> n >> word;
std::cout << n + 1 << " " << word << "\n"; // 18 apples
return 0;
}
Common pitfalls
- Comparing
find’s result with-1or storing it in anint; usestd::string::nposandsize_type. c_str()pointers are invalidated when the string is modified or destroyed."abc" + "def"does not compile: two string literals are pointers. One side must be astd::string.- Constructing from a null
const char*is undefined behavior. s[i]is unchecked;s.at(i)throwsstd::out_of_range.
Legacy vs modern
C++11 adds std::stoi/stod/to_string, raw string literals and move semantics (cheap returns). C++17’s std::string_view avoids copies for read-only parameters, and C++20 adds starts_with/ends_with.
Exercises
1. Write a function that returns s in upper case.
#include <cctype>
std::string upper(std::string s) {
for (std::size_t i = 0; i < s.size(); ++i) s[i] = std::toupper(static_cast<unsigned char>(s[i]));
return s;
}