🔤 Mastering `std::string`: Modern C++ Text Manipulation
Unlike error-prone C-style character arrays, the Standard Library std::string class (`
📦 Core Advantages Over C-Strings
- Dynamic Resizing: Automatically grows or shrinks in RAM as characters are added or removed.
- Memory Safety: Eliminates buffer overflow risks inherent in fixed-size character arrays.
- Intuitive Operators: Supports direct concatenation (`+`) and relational comparisons (`==`, `<`, `>`).
⚙️ Essential Member Methods
- length() / size(): Returns total character count.
- append() / push_back(): Adds characters or strings.
- substr(pos, len): Extracts substring segments.
- find(str): Searches for substrings and returns index or `string::npos`.
📊 End-to-End `std::string` Dynamic Allocation & Manipulation Workflow Diagram
1. Object Initialization
Declare `std::string name = "Nikita";`.
2. Dynamic Heap Allocation
Class allocates managed buffer on heap (with Small String Optimization cache).
3. Method Execution
Invoke methods (`substr`, `find`, `append`) or operators (`+`).
6. Console Output
Render results via `std::cout` stream.
5. Automatic Destruction
RAM automatically reclaimed when string object goes out of scope.
4. Buffer Reallocation
Automatically resizes heap buffer if string capacity is exceeded.
#include
#include
using namespace std;
int main() {
string firstName = "Aarav";
string middleName = "Kumar";
string lastName = "Sharma";
// Concatenate using '+' operator
string fullName = firstName + " " + middleName + " " + lastName;
cout << "--- Full Name Concatenation ---" << endl;
cout << "Combined Full Name: " << fullName << endl;
return 0;
}
#include
#include
using namespace std;
int main() {
string userPassword = "Secure#2026";
cout << "--- Password Length Validator ---" << endl;
if (userPassword.empty()) {
cout << "Error: Password cannot be empty." << endl;
} else if (userPassword.length() < 8) {
cout << "Error: Password must be at least 8 characters long." << endl;
} else {
cout << "Success: Password length (" << userPassword.length() << " chars) is valid." << endl;
}
return 0;
}
#include
#include
using namespace std;
int main() {
string cardNumber = "4532782910244892";
// Extract last 4 digits starting from index 12
string lastFourDigits = cardNumber.substr(12, 4);
string maskedCard = "XXXX-XXXX-XXXX-" + lastFourDigits;
cout << "--- Credit Card Masking ---" << endl;
cout << "Original Card : " << cardNumber << endl;
cout << "Masked Display: " << maskedCard << endl;
return 0;
}
#include
#include
using namespace std;
int main() {
string userEmail = "support@nikitainfotech.com";
size_t atPosition = userEmail.find('@');
cout << "--- Email Domain Parser ---" << endl;
if (atPosition != string::npos) {
string domain = userEmail.substr(atPosition + 1);
cout << "Email Address : " << userEmail << endl;
cout << "Extracted Domain: " << domain << endl;
} else {
cout << "Invalid email format." << endl;
}
return 0;
}
#include
#include
using namespace std;
int main() {
string comment = "This software is absolute junk!";
string targetWord = "junk";
string replacement = "fantastic";
size_t pos = comment.find(targetWord);
if (pos != string::npos) {
comment.replace(pos, targetWord.length(), replacement);
}
cout << "--- Content Moderation Filter ---" << endl;
cout << "Moderated Comment: " << comment << endl;
return 0;
}
#include
#include
using namespace std;
int main() {
string phoneNumber = "9876543210";
// Insert country code at index 0
phoneNumber.insert(0, "+91 ");
cout << "--- Phone Number Formatter ---" << endl;
cout << "Formatted Number: " << phoneNumber << endl;
// Erase country code prefix (+91 is 4 chars)
phoneNumber.erase(0, 4);
cout << "Erased Number : " << phoneNumber << endl;
return 0;
}
#include
#include
using namespace std;
int main() {
string userRole = "Administrator";
string requiredRole = "Administrator";
cout << "--- Role Authorization Check ---" << endl;
if (userRole == requiredRole) {
cout << "Access Granted: Administrative privileges unlocked." << endl;
} else {
cout << "Access Denied: Insufficient permissions." << endl;
}
return 0;
}
#include
#include
#include
using namespace std;
int main() {
string city = "pune maharashtra";
for (char &c : city) {
c = toupper(c);
}
cout << "--- Uppercase Transformation ---" << endl;
cout << "Capitalized City: " << city << endl;
return 0;
}
#include
#include
#include
using namespace std;
int main() {
string priceString = "4999.50";
string quantityString = "3";
double price = stod(priceString);
int quantity = stoi(quantityString);
double totalCost = price * quantity;
cout << "--- E-Commerce String-to-Numeric ---" << endl;
cout << "Unit Price : ₹" << fixed << setprecision(2) << price << endl;
cout << "Quantity : " << quantity << endl;
cout << "Total Cost : ₹" << totalCost << endl;
return 0;
}
#include
#include
using namespace std;
int main() {
int errorCode = 503;
long long transactionId = 981240091LL;
string logMessage = "[ERROR]: Server returned code " + to_string(errorCode) +
" for Transaction #" + to_string(transactionId);
cout << "--- Numeric to String Logging ---" << endl;
cout << logMessage << endl;
return 0;
}