Definition
📌 Strings
Unlike C, C++ has a proper string type: std::string (from the <string> header).
Syntax
syntax
#include <string>
string name = "text";
name.length();
name + otherString;Example
cpp
#include <iostream>
#include <string>
using namespace std;
int main() {
string name = "CodeyHub";
cout << "Name: " << name << endl;
cout << "Length: " << name.length() << endl;
return 0;
}Output
outputName: CodeyHub
Length: 8
Important Points
std::stringautomatically manages memory — no manual null terminators to worry about.- Use
+to concatenate two strings directly. ==works correctly for comparingstd::stringcontent (unlike C-style char arrays)..substr(),.find(), and.replace()are common built-in helper methods.
Common Mistakes
- Forgetting
#include <string>before usingstd::string. - Mixing C-style char arrays and
std::stringinconsistently in the same codebase. - Assuming
.length()and array indexing bounds are automatically checked — use.at()for safety.
Interview Tip
🎯 Before your interview
Be ready to contrast
std::string with C's char arrays: automatic memory management vs manual, and == works as expected.
