Lesson 4 of 45 · C++
Lesson 12: C‑Style Strings and std::string
Duration: 11 min
Lesson 4 of 45 · C++
Duration: 11 min
std::string\n\nA 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.\n\n---\n\n## C‑style example\ncpp\nchar name[20] = \"Alice\"; // null‑terminated automatically\nstd::cout << \"Name: \" << name << \" (length \" << std::strlen(name) << \")\\n\";\n\n// Concatenation with `strcat` (unsafe – may overflow)\nchar buffer[30] = \"Hello \";\nstd::strcat(buffer, name);\nstd::cout << buffer << '\\n';\n\n\n## std::string example\ncpp\nstd::string greeting = \"Hello \";\nstd::string name = \"Bob\";\nstd::string message = greeting + name + \"!\"; // automatic resizing\nstd::cout << message << \" (size \" << message.size() << \")\\n\";\n\n\nstd::string manages its own memory, provides a rich set of member functions (substr, find, replace), and works seamlessly with STL algorithms.\n\n> Tip: Prefer std::string for new code; only use C‑style strings when interacting with legacy APIs.\n\n---\n\n