Strings
C hands you raw, null-terminated character arrays and makes you manage their length and memory by hand. C++'s std::string, from the <string> header, wraps all of that up into a type that resizes itself, tracks its own length, and comes with a full set of built-in operations — the same upgrade std::vector gave you over C-style arrays.
Creating and concatenating strings
std::string supports the + operator directly, unlike C's character arrays, which need a function call just to concatenate:
#include <iostream> #include <string> int main() { std::string first = "Ada"; std::string last = "Lovelace"; std::string full = first + " " + last; std::cout << full << std::endl; std::cout << "Length: " << full.length() << std::endl; return 0; }
Ada Lovelace Length: 12
full.length() (equivalently full.size()) always reflects the string's true current length — no need for anything like C's strlen, since a std::string already knows how long it is.
substr and find
.substr(start, count) pulls out a piece of a string, and .find() searches for one string inside another, returning the starting index or std::string::npos if there's no match:
#include <iostream> #include <string> int main() { std::string email = "maya@example.com"; size_t at = email.find("@"); std::string username = email.substr(0, at); std::string domain = email.substr(at + 1); std::cout << "Username: " << username << std::endl; std::cout << "Domain: " << domain << std::endl; return 0; }
Username: maya Domain: example.com
email.find("@") returns the index of the @ character. substr(0, at) takes everything from the start up to (but not including) that index, and substr(at + 1) — with no second argument — takes everything from just past the @ to the end of the string.
Comparing strings
Unlike C-style strings, which need strcmp, std::string supports == and the other comparison operators directly:
#include <iostream> #include <string> int main() { std::string input = "yes"; if (input == "yes") { std::cout << "Confirmed." << std::endl; } else { std::cout << "Not confirmed." << std::endl; } return 0; }
Confirmed.
input == "yes" compares the actual characters, exactly the way you'd expect — a huge relief coming from C, where == on two character arrays compares their memory addresses, not their contents.
"hello" is still a const char* under the hood, not a std::string — C++ converts it automatically in most contexts (like input == "yes" above), but if you're passing strings to older C-style APIs, .c_str() converts a std::string back into that raw const char* form.