std::string (from <string>) is C++'s full-featured replacement for C's raw, null-terminated char* strings, handling memory management automatically.
#include <string>
std::string name = "Rahim";
std::string greeting = "Hello, " + name + "!"; // + concatenates directly
std::cout << greeting.length() << "\n"; // 13 — no strlen() needed
std::cout << greeting.substr(7, 5) << "\n"; // "Rahim" — start index, length
if (greeting.find("Rahim") != std::string::npos) {
std::cout << "Found!\n";
}
int n = 42;
std::string numStr = std::to_string(n); // int -> string
int back = std::stoi(numStr); // string -> int
Unlike C, where building a greeting from pieces requires manually managing buffer sizes with strcpy/strcat and constantly risking overflow, std::string's + operator concatenates safely and automatically resizes its internal buffer as needed — the class manages its own memory, so there's no equivalent of forgetting to free() a string.
.length() (or the equivalent .size()) replaces strlen(); .substr(start, length) extracts a portion; .find() searches for a substring and returns std::string::npos (a special "not found" sentinel value) rather than -1 or NULL when nothing matches — always compare against std::string::npos explicitly rather than assuming a specific numeric value. std::to_string() and std::stoi()/std::stod() convert between numbers and strings without needing sprintf/sscanf-style format strings.