Include Header
#include <string>
Declaration
std::string str1; // Empty string
std::string str2 = "Hello"; // Initialize with literal
std::string str3("World"); // Constructor form
std::string str4(5, 'x'); // "xxxxx"
String Concatenation
std::string result = str1 + str2; // Combine strings
str1 += " more"; // Append to existing string
Access Characters
char ch = str1[index]; // Direct access
char ch = str1.at(index); // Bounds-checked access
Slice / Substring
std::string sub = str1.substr(start_index); // From index to end
std::string sub = str1.substr(start_index, length); // Substring with length
Remove Characters
str1.pop_back(); // Remove last character
str1.erase(index, count); // Remove count chars from index
str1.clear(); // Clear entire string
Check if Empty
if (str1.empty()) {
// String is empty
}
Iterate Through Characters
for (char c : str1) {
std::cout << c << std::endl;
}
Size and Capacity
str1.size(); // Number of characters
str1.length(); // Same as size()
str1.capacity(); // Allocated memory
str1.resize(new_size); // Resize string
Reverse String
#include <algorithm>
std::reverse(str1.begin(), str1.end());
Find Substring or Character
std::size_t pos = str1.find("sub");
if (pos != std::string::npos) {
// Found at position `pos`
}
Replace Substring
str1.replace(pos, len, "new_sub"); // Replace len characters at pos
Compare Strings
if (str1 == str2) {
// Strings are equal
}
if (str1 < str2) {
// Lexicographically less
}
Convert to C-style String
const char* c_str = str1.c_str(); // Null-terminated C-string
Construct from C-string
std::string str("abc"); // From literal
std::string str(cstr, length); // From char array with length
Split String on Delimiter
#include <vector>
#include <sstream>
std::vector<std::string> split(const std::string& s, char delimiter) {
std::vector<std::string> tokens;
std::stringstream ss(s);
std::string item;
while (std::getline(ss, item, delimiter)) {
tokens.push_back(item);
}
return tokens;
}
Trim Whitespace
#include <algorithm>
#include <cctype>
std::string trim(const std::string& s) {
auto start = std::find_if_not(s.begin(), s.end(), ::isspace);
auto end = std::find_if_not(s.rbegin(), s.rend(), ::isspace).base();
return (start < end) ? std::string(start, end) : "";
}