MODULE 4: ARRAYS & STRINGS 4.3 C++ `std::string` Class (``, Methods, Operations)

Industrial reference manual: Comprehensive architectural breakdown of the C++ Standard Library `std::string` class, dynamic memory allocation, member methods (`length`, `append`, `substr`, `find`), operator overloading, and 10 production-aligned real-world code implementations with outputs.

🔤 Mastering `std::string`: Modern C++ Text Manipulation

Unlike error-prone C-style character arrays, the Standard Library std::string class (``) provides a robust, safe, and dynamic string type. It automatically manages memory allocation, handles resizing dynamically, and supports intuitive operator overloading (`+`, `+=`, `==`).

📦 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.

1. String Concatenation Using Operator Overloading (`+`)
Combines first name, middle name, and last name strings using the intuitive plus operator (`+`).
C++ / String Concatenation
#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;
}
--- Full Name Concatenation --- Combined Full Name: Aarav Kumar Sharma
2. Password Strength Validation Using `.length()` and `.empty()`
Validates user password length and emptiness using `std::string` member methods.
C++ / Password Length Check (`length`)
#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;
}
--- Password Length Validator --- Success: Password length (11 chars) is valid.
3. Substring Extraction Using `.substr()` for Masking Credit Cards
Masks sensitive credit card numbers by extracting the last 4 digits using `.substr()`.
C++ / Substring Masking (`substr`)
#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;
}
--- Credit Card Masking --- Original Card : 4532782910244892 Masked Display: XXXX-XXXX-XXXX-4892
4. Substring Searching Using `.find()` for URL Domain Parsing
Locates specific character positions (`@` or `.com`) in URLs or emails using `.find()`.
C++ / Substring Search (`find`)
#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;
}
--- Email Domain Parser --- Email Address : support@nikitainfotech.com Extracted Domain: nikitainfotech.com
5. Text Replacement Using `.replace()` for Profanity Censorship
Replaces flagged words in user feedback comments using the `.replace()` member method.
C++ / Text Replacement (`replace`)
#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;
}
--- Content Moderation Filter --- Moderated Comment: This software is absolute fantastic!
6. String Insertion and Erasure (`.insert()` and `.erase()`)
Inserts country code prefixes and erases formatting symbols from phone number strings.
C++ / Insert and Erase Methods
#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;
}
--- Phone Number Formatter --- Formatted Number: +91 9876543210 Erased Number : 9876543210
7. Lexicographical Comparison (`==`, `<`, `>`) for User Role Authorization
Compares user permission roles using standard relational comparison operators.
C++ / Relational String Comparison
#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;
}
--- Role Authorization Check --- Access Granted: Administrative privileges unlocked.
8. Iterating Over `std::string` Characters for Case Conversion
Iterates through string characters using range-based loops to convert text to uppercase.
C++ / Character Iteration & Transformation
#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;
}
--- Uppercase Transformation --- Capitalized City: PUNE MAHARASHTRA
9. Converting `std::string` to Numeric Values Using `stoi()`
Converts string-encoded price data into integer and double values using `stoi()` and `stod()`.
C++ / String to Numeric Conversion (`stoi`)
#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;
}
--- E-Commerce String-to-Numeric --- Unit Price : ₹4999.50 Quantity : 3 Total Cost : ₹14998.50
10. Converting Numeric Values to `std::string` Using `to_string()`
Converts integer error codes and transaction IDs into strings using `to_string()` for logging.
C++ / Numeric to String Conversion (`to_string`)
#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;
}
--- Numeric to String Logging --- [ERROR]: Server returned code 503 for Transaction #981240091