Lesson 12 of 45
C++Lesson 12: C‑Style Strings and std::string
11 min
Course progress27%
What you'll learn
Keep these ideas in mind as you work through the lesson.
Lesson 12 of 45
C++11 min
Keep these ideas in mind as you work through the lesson.
std::stringA C‑style string is a null‑terminated character array (char[]). The C++ Standard Library augments this with std::string, a more convenient, dynamic, and safer alternative.
char name[20] = \"Alice\"; // null‑terminated automatically
std::cout << \"Name: \" << name << \" (length \" << std::strlen(name) << \")\
\";
// Concatenation with `strcat` (unsafe – may overflow)
char buffer[30] = \"Hello \";
std::strcat(buffer, name);
std::cout << buffer << '\
';
std::string examplestd::string greeting = \"Hello \";
std::string name = \"Bob\";
std::string message = greeting + name + \"!\"; // automatic resizing
std::cout << message << \" (size \" << message.size() << \")\
\";
std::string manages its own memory, provides a rich set of member functions (substr, find, replace), and works seamlessly with STL algorithms.
Tip: Prefer
std::stringfor new code; only use C‑style strings when interacting with legacy APIs.