std::string Methods in C++
std::string owns and manages its character storage, growing as needed — concatenation with +, comparison with ==, and bounds-checked at() replace the entire <cstring> minefield. Size is always available (size()/length()), and empty() reads clearer than comparing against zero.
The workhorse methods: substr extracts, find/rfind locate (returning npos on failure — always compare against std::string::npos, never -1), replace/erase/insert edit in place, and stoi/stod parse numbers. Iterators and range-based for work character by character.
+ and == just work
std::string a = "foo" + bar; concatenates and if (a == b) compares contents — no strcmp, no manual allocation.
Search with find, test npos
s.find("needle") returns the position or std::string::npos when absent — the only correct failure test.
Edit in place
substr(pos, len) copies a slice; erase, insert, and replace modify the string itself without manual shifting.
Convert with stoX/to_string
std::stoi("42") parses, std::to_string(42) stringifies — the civilized replacements for atoi and sprintf.
#include <iostream>#include <string> int main() { std::string s = "hello world"; std::cout << s.size() << std::endl; std::cout << s.substr(6, 5) << std::endl; std::cout << (s.find("world") != std::string::npos) << std::endl; return 0;}Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in C++ yourself — building beats watching.