C++ Strings
std::string — The C++ Way
C++ provides std::string from <string> — a full-featured class that manages memory automatically. Unlike C-style char arrays, std::string can grow dynamically, supports operators, and has dozens of useful methods.
#include <iostream>
#include <string>
using namespace std;
int main() {
string s1 = "Hello";
string s2 = "World";
// Concatenation
string s3 = s1 + ", " + s2 + "!";
cout << s3 << endl; // Hello, World!
// Length
cout << "Length: " << s3.length() << endl; // 13
cout << "Size: " << s3.size() << endl; // same as length()
// Access characters
cout << "First: " << s3[0] << endl; // H
cout << "Last: " << s3.back() << endl; // !
cout << "At(6): " << s3.at(6) << endl; // W (bounds-checked)
// Comparison (lexicographic)
cout << boolalpha;
cout << (s1 == "Hello") << endl; // true
cout << (s1 < s2) << endl; // true (H < W)
// Append
s1 += " there";
cout << s1 << endl; // Hello there
// Empty check
string empty = "";
cout << "Empty: " << empty.empty() << endl; // true
return 0;
}
Common String Methods
| Method | Description | Example |
|---|---|---|
substr(pos, len) | Extract substring | "Hello".substr(1,3) → "ell" |
find(str) | Find first occurrence | "Hello".find("ll") → 2 |
replace(pos,len,str) | Replace portion | s.replace(0,5,"Hi") |
erase(pos, len) | Remove characters | s.erase(0, 3) |
insert(pos, str) | Insert at position | s.insert(5, " World") |
c_str() | Convert to C-string | s.c_str() → const char* |
to_string(n) | Number to string | to_string(42) → "42" |
stoi(s) | String to int | stoi("42") → 42 |
stod(s) | String to double | stod("3.14") → 3.14 |
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main() {
string s = "Hello, World!";
// substr
cout << s.substr(7, 5) << endl; // World
// find — returns string::npos if not found
size_t pos = s.find("World");
if (pos != string::npos)
cout << "Found at: " << pos << endl; // 7
// replace
s.replace(7, 5, "C++");
cout << s << endl; // Hello, C++!
// Convert to upper/lower
string upper = s;
transform(upper.begin(), upper.end(), upper.begin(), ::toupper);
cout << upper << endl; // HELLO, C++!
// Number conversions
int n = stoi("42");
double d = stod("3.14");
string ns = to_string(100);
cout << n << " " << d << " " << ns << endl;
// Split by delimiter (manual)
string csv = "Alice,Bob,Charlie";
size_t start = 0, end;
while ((end = csv.find(',', start)) != string::npos) {
cout << csv.substr(start, end - start) << endl;
start = end + 1;
}
cout << csv.substr(start) << endl; // Charlie
return 0;
}