cpp

examples

examples.cpp⚙️
/**
 * C++ Strings - Comprehensive Examples
 * 
 * This file demonstrates string operations in C++ with detailed explanations.
 * Each function focuses on a specific aspect of working with strings.
 * 
 * Topics covered:
 * 1. String Creation and Initialization
 * 2. Accessing Characters
 * 3. String Concatenation
 * 4. Searching and Finding
 * 5. Modifying Strings
 * 6. String Comparison
 * 7. String Conversion
 * 8. String Algorithms
 * 9. C-String Interoperability
 * 10. Practical Examples
 * 
 * Compile: g++ -std=c++17 -Wall -Wextra examples.cpp -o examples
 * Run: ./examples
 */

#include <iostream>
#include <string>
#include <algorithm>
#include <cctype>
#include <sstream>
#include <iomanip>
#include <vector>
#include <regex>
#include <cstring>

using namespace std;

// ============================================================
// 1. String Creation and Initialization
// ============================================================
void demonstrateCreation() {
    cout << "\n╔═══════════════════════════════════════════════════════════╗" << endl;
    cout << "║       1. STRING CREATION AND INITIALIZATION               ║" << endl;
    cout << "╚═══════════════════════════════════════════════════════════╝\n" << endl;
    
    // Default constructor
    string s1;
    cout << "Default constructor: \"" << s1 << "\" (empty)" << endl;
    
    // From C-string
    string s2 = "Hello";
    string s3("World");
    cout << "From C-string: \"" << s2 << "\" and \"" << s3 << "\"" << endl;
    
    // Fill constructor
    string s4(5, '*');
    string s5(10, '-');
    cout << "Fill constructor: \"" << s4 << "\" and \"" << s5 << "\"" << endl;
    
    // Copy constructor
    string s6 = s2;
    cout << "Copy constructor: \"" << s6 << "\"" << endl;
    
    // Substring constructor
    string full = "Hello, World!";
    string s7(full, 7, 5);  // Start at 7, length 5
    cout << "Substring constructor: \"" << s7 << "\" from \"" << full << "\"" << endl;
    
    // Range constructor
    string s8(full.begin(), full.begin() + 5);
    cout << "Range constructor: \"" << s8 << "\"" << endl;
    
    // Initializer list
    string s9 = {'C', '+', '+'};
    cout << "Initializer list: \"" << s9 << "\"" << endl;
    
    // Move constructor
    string temp = "Move me";
    string s10 = move(temp);
    cout << "After move: s10 = \"" << s10 << "\", temp = \"" << temp << "\" (empty)" << endl;
    
    // Raw string literal
    string s11 = R"(Path: C:\Users\name)";
    cout << "Raw string: \"" << s11 << "\"" << endl;
    
    // Multi-line raw string
    string s12 = R"(Line 1
Line 2
Line 3)";
    cout << "Multi-line raw string:\n" << s12 << endl;
}

// ============================================================
// 2. Accessing Characters
// ============================================================
void demonstrateAccess() {
    cout << "\n╔═══════════════════════════════════════════════════════════╗" << endl;
    cout << "║              2. ACCESSING CHARACTERS                      ║" << endl;
    cout << "╚═══════════════════════════════════════════════════════════╝\n" << endl;
    
    string s = "Hello, World!";
    cout << "String: \"" << s << "\"" << endl;
    
    // Using operator[]
    cout << "\nUsing operator[]:" << endl;
    cout << "  s[0] = '" << s[0] << "'" << endl;
    cout << "  s[7] = '" << s[7] << "'" << endl;
    cout << "  s[s.size()-1] = '" << s[s.size()-1] << "'" << endl;
    
    // Using at() with bounds checking
    cout << "\nUsing at():" << endl;
    cout << "  s.at(0) = '" << s.at(0) << "'" << endl;
    
    try {
        cout << "  Trying s.at(100)... ";
        char c = s.at(100);
        cout << c << endl;
    } catch (const out_of_range& e) {
        cout << "Exception: " << e.what() << endl;
    }
    
    // front() and back()
    cout << "\nUsing front() and back():" << endl;
    cout << "  s.front() = '" << s.front() << "'" << endl;
    cout << "  s.back() = '" << s.back() << "'" << endl;
    
    // Modifying characters
    cout << "\nModifying characters:" << endl;
    s[0] = 'J';
    s.back() = '?';
    cout << "  After s[0]='J' and s.back()='?': \"" << s << "\"" << endl;
    
    // Iteration methods
    cout << "\nIteration methods:" << endl;
    
    s = "Hello";
    cout << "  Index-based: ";
    for (size_t i = 0; i < s.size(); i++) {
        cout << s[i] << " ";
    }
    cout << endl;
    
    cout << "  Range-based: ";
    for (char c : s) {
        cout << c << " ";
    }
    cout << endl;
    
    cout << "  Iterator-based: ";
    for (auto it = s.begin(); it != s.end(); ++it) {
        cout << *it << " ";
    }
    cout << endl;
    
    cout << "  Reverse: ";
    for (auto rit = s.rbegin(); rit != s.rend(); ++rit) {
        cout << *rit << " ";
    }
    cout << endl;
}

// ============================================================
// 3. String Concatenation
// ============================================================
void demonstrateConcatenation() {
    cout << "\n╔═══════════════════════════════════════════════════════════╗" << endl;
    cout << "║            3. STRING CONCATENATION                        ║" << endl;
    cout << "╚═══════════════════════════════════════════════════════════╝\n" << endl;
    
    string a = "Hello";
    string b = "World";
    
    // Using + operator
    cout << "Using + operator:" << endl;
    string c = a + " " + b + "!";
    cout << "  a + \" \" + b + \"!\" = \"" << c << "\"" << endl;
    
    // Using += operator
    cout << "\nUsing += operator:" << endl;
    string d = "Say: ";
    d += a;
    d += " ";
    d += b;
    cout << "  After +=: \"" << d << "\"" << endl;
    
    // Using append()
    cout << "\nUsing append():" << endl;
    string e = "Start";
    
    e.append(" - ");
    cout << "  append(\" - \"): \"" << e << "\"" << endl;
    
    e.append("End", 3);  // First 3 chars
    cout << "  append(\"End\", 3): \"" << e << "\"" << endl;
    
    e.append(3, '!');    // 3 exclamation marks
    cout << "  append(3, '!'): \"" << e << "\"" << endl;
    
    // Chained append
    string f;
    f.append("One").append("-").append("Two").append("-").append("Three");
    cout << "  Chained append: \"" << f << "\"" << endl;
    
    // push_back for single characters
    cout << "\nUsing push_back():" << endl;
    string g = "AB";
    g.push_back('C');
    g.push_back('D');
    cout << "  After push_back('C', 'D'): \"" << g << "\"" << endl;
    
    // Building string efficiently
    cout << "\nEfficient string building:" << endl;
    string h;
    h.reserve(50);  // Pre-allocate
    cout << "  Capacity after reserve(50): " << h.capacity() << endl;
    
    for (int i = 0; i < 10; i++) {
        h += to_string(i);
    }
    cout << "  Result: \"" << h << "\"" << endl;
}

// ============================================================
// 4. Searching and Finding
// ============================================================
void demonstrateSearching() {
    cout << "\n╔═══════════════════════════════════════════════════════════╗" << endl;
    cout << "║            4. SEARCHING AND FINDING                       ║" << endl;
    cout << "╚═══════════════════════════════════════════════════════════╝\n" << endl;
    
    string s = "Hello, World! Hello, C++!";
    cout << "String: \"" << s << "\"" << endl;
    
    // find() - first occurrence
    cout << "\nfind() - first occurrence:" << endl;
    size_t pos = s.find("Hello");
    cout << "  find(\"Hello\") = " << pos << endl;
    
    pos = s.find("Hello", 10);  // Start from index 10
    cout << "  find(\"Hello\", 10) = " << pos << endl;
    
    pos = s.find('o');
    cout << "  find('o') = " << pos << endl;
    
    pos = s.find("xyz");
    cout << "  find(\"xyz\") = " << (pos == string::npos ? "npos (not found)" : to_string(pos)) << endl;
    
    // rfind() - last occurrence
    cout << "\nrfind() - last occurrence:" << endl;
    pos = s.rfind("Hello");
    cout << "  rfind(\"Hello\") = " << pos << endl;
    
    pos = s.rfind('o');
    cout << "  rfind('o') = " << pos << endl;
    
    // find_first_of() - any character from set
    cout << "\nfind_first_of() - any character from set:" << endl;
    pos = s.find_first_of("aeiou");
    cout << "  find_first_of(\"aeiou\") = " << pos << " ('" << s[pos] << "')" << endl;
    
    pos = s.find_first_of("!+,");
    cout << "  find_first_of(\"!+,\") = " << pos << " ('" << s[pos] << "')" << endl;
    
    // find_last_of()
    cout << "\nfind_last_of():" << endl;
    pos = s.find_last_of("aeiou");
    cout << "  find_last_of(\"aeiou\") = " << pos << " ('" << s[pos] << "')" << endl;
    
    // find_first_not_of() - useful for trimming
    cout << "\nfind_first_not_of() / find_last_not_of():" << endl;
    string padded = "   trim me   ";
    cout << "  Padded string: \"" << padded << "\"" << endl;
    
    size_t start = padded.find_first_not_of(" ");
    size_t end = padded.find_last_not_of(" ");
    cout << "  First non-space: " << start << ", Last non-space: " << end << endl;
    
    string trimmed = padded.substr(start, end - start + 1);
    cout << "  Trimmed: \"" << trimmed << "\"" << endl;
    
    // Finding all occurrences
    cout << "\nFinding all occurrences of 'o':" << endl;
    pos = 0;
    while ((pos = s.find('o', pos)) != string::npos) {
        cout << "  Found at position: " << pos << endl;
        pos++;  // Move past this occurrence
    }
}

// ============================================================
// 5. Modifying Strings
// ============================================================
void demonstrateModification() {
    cout << "\n╔═══════════════════════════════════════════════════════════╗" << endl;
    cout << "║              5. MODIFYING STRINGS                         ║" << endl;
    cout << "╚═══════════════════════════════════════════════════════════╝\n" << endl;
    
    // insert()
    cout << "insert():" << endl;
    string s1 = "Hello World";
    s1.insert(5, ",");
    cout << "  \"Hello World\" -> insert(5, \",\") -> \"" << s1 << "\"" << endl;
    
    s1.insert(0, "Say: ");
    cout << "  insert(0, \"Say: \") -> \"" << s1 << "\"" << endl;
    
    // erase()
    cout << "\nerase():" << endl;
    string s2 = "Hello, World!";
    s2.erase(5, 2);  // Erase 2 chars starting at position 5
    cout << "  \"Hello, World!\" -> erase(5, 2) -> \"" << s2 << "\"" << endl;
    
    s2.erase(s2.size() - 1);  // Erase last character
    cout << "  erase last char -> \"" << s2 << "\"" << endl;
    
    // replace()
    cout << "\nreplace():" << endl;
    string s3 = "Hello, World!";
    s3.replace(7, 5, "C++");
    cout << "  \"Hello, World!\" -> replace(7, 5, \"C++\") -> \"" << s3 << "\"" << endl;
    
    // Replace all occurrences
    cout << "\nReplace all occurrences:" << endl;
    string s4 = "cat and cat and cat";
    cout << "  Original: \"" << s4 << "\"" << endl;
    
    string target = "cat";
    string replacement = "dog";
    size_t pos = 0;
    while ((pos = s4.find(target, pos)) != string::npos) {
        s4.replace(pos, target.length(), replacement);
        pos += replacement.length();
    }
    cout << "  After replacing 'cat' with 'dog': \"" << s4 << "\"" << endl;
    
    // pop_back()
    cout << "\npop_back():" << endl;
    string s5 = "Hello!!";
    s5.pop_back();
    s5.pop_back();
    cout << "  \"Hello!!\" -> 2x pop_back() -> \"" << s5 << "\"" << endl;
    
    // resize()
    cout << "\nresize():" << endl;
    string s6 = "Hello";
    s6.resize(10, '-');
    cout << "  \"Hello\" -> resize(10, '-') -> \"" << s6 << "\"" << endl;
    
    s6.resize(3);
    cout << "  resize(3) -> \"" << s6 << "\"" << endl;
    
    // clear()
    cout << "\nclear():" << endl;
    string s7 = "Clear me";
    cout << "  Before: \"" << s7 << "\", size = " << s7.size() << endl;
    s7.clear();
    cout << "  After: \"" << s7 << "\", size = " << s7.size() << endl;
    
    // Case conversion
    cout << "\nCase conversion:" << endl;
    string s8 = "Hello World";
    
    // To uppercase
    transform(s8.begin(), s8.end(), s8.begin(), ::toupper);
    cout << "  toupper: \"" << s8 << "\"" << endl;
    
    // To lowercase
    transform(s8.begin(), s8.end(), s8.begin(), ::tolower);
    cout << "  tolower: \"" << s8 << "\"" << endl;
}

// ============================================================
// 6. String Comparison
// ============================================================
void demonstrateComparison() {
    cout << "\n╔═══════════════════════════════════════════════════════════╗" << endl;
    cout << "║              6. STRING COMPARISON                         ║" << endl;
    cout << "╚═══════════════════════════════════════════════════════════╝\n" << endl;
    
    string a = "apple";
    string b = "banana";
    string c = "apple";
    
    // Comparison operators
    cout << "Comparison operators:" << endl;
    cout << "  a = \"" << a << "\", b = \"" << b << "\", c = \"" << c << "\"" << endl;
    cout << boolalpha;
    cout << "  a == c: " << (a == c) << endl;
    cout << "  a == b: " << (a == b) << endl;
    cout << "  a != b: " << (a != b) << endl;
    cout << "  a < b:  " << (a < b) << " (lexicographic)" << endl;
    cout << "  a > b:  " << (a > b) << endl;
    cout << "  a <= c: " << (a <= c) << endl;
    
    // compare() method
    cout << "\ncompare() method:" << endl;
    int result = a.compare(b);
    cout << "  a.compare(b) = " << result << " (< 0 means a comes before b)" << endl;
    
    result = a.compare(c);
    cout << "  a.compare(c) = " << result << " (0 means equal)" << endl;
    
    result = b.compare(a);
    cout << "  b.compare(a) = " << result << " (> 0 means b comes after a)" << endl;
    
    // Partial comparison
    string full = "Hello, World";
    cout << "\nPartial comparison:" << endl;
    cout << "  full = \"" << full << "\"" << endl;
    result = full.compare(0, 5, "Hello");
    cout << "  full.compare(0, 5, \"Hello\") = " << result << " (0 = match)" << endl;
    
    // Case-insensitive comparison
    cout << "\nCase-insensitive comparison:" << endl;
    string s1 = "Hello";
    string s2 = "HELLO";
    
    auto caseInsensitiveEqual = [](const string& a, const string& b) {
        if (a.size() != b.size()) return false;
        return equal(a.begin(), a.end(), b.begin(),
            [](char c1, char c2) {
                return tolower(c1) == tolower(c2);
            });
    };
    
    cout << "  \"" << s1 << "\" equals \"" << s2 << "\" (case-insensitive): " 
         << caseInsensitiveEqual(s1, s2) << endl;
}

// ============================================================
// 7. String Conversion
// ============================================================
void demonstrateConversion() {
    cout << "\n╔═══════════════════════════════════════════════════════════╗" << endl;
    cout << "║              7. STRING CONVERSION                         ║" << endl;
    cout << "╚═══════════════════════════════════════════════════════════╝\n" << endl;
    
    // String to numbers
    cout << "String to numbers:" << endl;
    
    int i = stoi("42");
    cout << "  stoi(\"42\") = " << i << endl;
    
    long l = stol("123456789");
    cout << "  stol(\"123456789\") = " << l << endl;
    
    double d = stod("3.14159");
    cout << "  stod(\"3.14159\") = " << d << endl;
    
    float f = stof("2.5");
    cout << "  stof(\"2.5\") = " << f << endl;
    
    // With different bases
    cout << "\nDifferent bases:" << endl;
    int hex = stoi("FF", nullptr, 16);
    cout << "  stoi(\"FF\", nullptr, 16) = " << hex << endl;
    
    int bin = stoi("1010", nullptr, 2);
    cout << "  stoi(\"1010\", nullptr, 2) = " << bin << endl;
    
    int oct = stoi("77", nullptr, 8);
    cout << "  stoi(\"77\", nullptr, 8) = " << oct << endl;
    
    // Numbers to string
    cout << "\nNumbers to string:" << endl;
    cout << "  to_string(42) = \"" << to_string(42) << "\"" << endl;
    cout << "  to_string(3.14159) = \"" << to_string(3.14159) << "\"" << endl;
    cout << "  to_string(-100) = \"" << to_string(-100) << "\"" << endl;
    
    // Using stringstream for formatting
    cout << "\nUsing stringstream:" << endl;
    stringstream ss;
    ss << fixed << setprecision(2) << 3.14159;
    cout << "  3.14159 with 2 decimals: \"" << ss.str() << "\"" << endl;
    
    ss.str("");  // Clear
    ss << setw(10) << setfill('0') << 42;
    cout << "  42 padded to width 10: \"" << ss.str() << "\"" << endl;
    
    // Parsing strings with stringstream
    cout << "\nParsing with stringstream:" << endl;
    stringstream parser("John 25 3.5");
    string name;
    int age;
    double gpa;
    parser >> name >> age >> gpa;
    cout << "  Parsed: name=\"" << name << "\", age=" << age << ", gpa=" << gpa << endl;
    
    // Error handling
    cout << "\nError handling:" << endl;
    try {
        int x = stoi("not a number");
        (void)x;
    } catch (const invalid_argument& e) {
        cout << "  stoi(\"not a number\"): invalid_argument - " << e.what() << endl;
    }
    
    try {
        int x = stoi("99999999999999999999");
        (void)x;
    } catch (const out_of_range& e) {
        cout << "  stoi(large number): out_of_range - " << e.what() << endl;
    }
}

// ============================================================
// 8. String Algorithms
// ============================================================
void demonstrateAlgorithms() {
    cout << "\n╔═══════════════════════════════════════════════════════════╗" << endl;
    cout << "║             8. STRING ALGORITHMS                          ║" << endl;
    cout << "╚═══════════════════════════════════════════════════════════╝\n" << endl;
    
    // Reverse
    cout << "reverse():" << endl;
    string s1 = "Hello";
    reverse(s1.begin(), s1.end());
    cout << "  \"Hello\" reversed: \"" << s1 << "\"" << endl;
    
    // Sort characters
    cout << "\nsort():" << endl;
    string s2 = "dcba";
    sort(s2.begin(), s2.end());
    cout << "  \"dcba\" sorted: \"" << s2 << "\"" << endl;
    
    // Check if palindrome
    cout << "\nPalindrome check:" << endl;
    auto isPalindrome = [](const string& s) {
        return equal(s.begin(), s.begin() + s.size()/2, s.rbegin());
    };
    
    cout << "  \"radar\" is palindrome: " << boolalpha << isPalindrome("radar") << endl;
    cout << "  \"hello\" is palindrome: " << isPalindrome("hello") << endl;
    
    // Count characters
    cout << "\ncount():" << endl;
    string s3 = "Mississippi";
    int count_s = count(s3.begin(), s3.end(), 's');
    int count_i = count(s3.begin(), s3.end(), 'i');
    cout << "  In \"" << s3 << "\": 's' appears " << count_s << " times, 'i' appears " << count_i << " times" << endl;
    
    // Remove characters (erase-remove idiom)
    cout << "\nRemove all vowels (erase-remove):" << endl;
    string s4 = "Hello World";
    cout << "  Original: \"" << s4 << "\"" << endl;
    s4.erase(remove_if(s4.begin(), s4.end(), [](char c) {
        return string("aeiouAEIOU").find(c) != string::npos;
    }), s4.end());
    cout << "  Without vowels: \"" << s4 << "\"" << endl;
    
    // Transform (apply function to each character)
    cout << "\ntransform():" << endl;
    string s5 = "Hello";
    transform(s5.begin(), s5.end(), s5.begin(), [](char c) {
        return (c == 'l') ? 'L' : c;
    });
    cout << "  Replace 'l' with 'L': \"" << s5 << "\"" << endl;
    
    // Rotate
    cout << "\nrotate():" << endl;
    string s6 = "abcdef";
    cout << "  Original: \"" << s6 << "\"" << endl;
    rotate(s6.begin(), s6.begin() + 2, s6.end());
    cout << "  Rotate left by 2: \"" << s6 << "\"" << endl;
    
    // Replace
    cout << "\nreplace():" << endl;
    string s7 = "banana";
    replace(s7.begin(), s7.end(), 'a', 'o');
    cout << "  \"banana\" with 'a' replaced by 'o': \"" << s7 << "\"" << endl;
    
    // Unique
    cout << "\nunique() (on sorted string):" << endl;
    string s8 = "aabbccdd";
    auto newEnd = unique(s8.begin(), s8.end());
    s8.erase(newEnd, s8.end());
    cout << "  \"aabbccdd\" unique: \"" << s8 << "\"" << endl;
}

// ============================================================
// 9. C-String Interoperability
// ============================================================
void demonstrateCStringInterop() {
    cout << "\n╔═══════════════════════════════════════════════════════════╗" << endl;
    cout << "║          9. C-STRING INTEROPERABILITY                     ║" << endl;
    cout << "╚═══════════════════════════════════════════════════════════╝\n" << endl;
    
    // c_str() - Get null-terminated C-string
    cout << "c_str():" << endl;
    string s = "Hello";
    const char* cstr = s.c_str();
    cout << "  std::string: \"" << s << "\"" << endl;
    cout << "  C-string: \"" << cstr << "\"" << endl;
    cout << "  Using printf: ";
    printf("%s\n", s.c_str());
    
    // data() - Similar to c_str()
    cout << "\ndata():" << endl;
    const char* data = s.data();
    cout << "  s.data(): \"" << data << "\"" << endl;
    
    // C-string to std::string
    cout << "\nC-string to std::string:" << endl;
    const char* cString = "From C";
    string cppString = cString;
    cout << "  Converted: \"" << cppString << "\"" << endl;
    
    // Using C string functions
    cout << "\nUsing C string functions:" << endl;
    cout << "  strlen(s.c_str()) = " << strlen(s.c_str()) << endl;
    
    char buffer[100];
    strcpy(buffer, s.c_str());
    cout << "  strcpy to buffer: \"" << buffer << "\"" << endl;
    
    // copy() method
    cout << "\ncopy() method:" << endl;
    string source = "Hello, World!";
    char dest[20];
    size_t copied = source.copy(dest, 5, 0);  // Copy 5 chars from position 0
    dest[copied] = '\0';  // Null-terminate manually!
    cout << "  Copied " << copied << " characters: \"" << dest << "\"" << endl;
    
    // Working with legacy C APIs
    cout << "\nWorking with legacy C APIs:" << endl;
    
    // Example: Reading into std::string
    string result;
    result.resize(100);
    // Simulate: readFromCAPI(result.data(), result.size());
    snprintf(result.data(), result.size(), "Data from C API");
    result.resize(strlen(result.c_str()));  // Shrink to actual size
    cout << "  After C API call: \"" << result << "\"" << endl;
}

// ============================================================
// 10. Practical Examples
// ============================================================
void demonstratePractical() {
    cout << "\n╔═══════════════════════════════════════════════════════════╗" << endl;
    cout << "║            10. PRACTICAL EXAMPLES                         ║" << endl;
    cout << "╚═══════════════════════════════════════════════════════════╝\n" << endl;
    
    // Example 1: Trim whitespace
    cout << "Example 1: Trim whitespace" << endl;
    auto trim = [](const string& str) {
        size_t start = str.find_first_not_of(" \t\n\r");
        if (start == string::npos) return string("");
        size_t end = str.find_last_not_of(" \t\n\r");
        return str.substr(start, end - start + 1);
    };
    
    string padded = "   Hello World   ";
    cout << "  Original: \"" << padded << "\"" << endl;
    cout << "  Trimmed:  \"" << trim(padded) << "\"" << endl;
    
    // Example 2: Split string
    cout << "\nExample 2: Split string by delimiter" << endl;
    auto split = [](const string& str, char delimiter) {
        vector<string> tokens;
        stringstream ss(str);
        string token;
        while (getline(ss, token, delimiter)) {
            tokens.push_back(token);
        }
        return tokens;
    };
    
    string csv = "apple,banana,cherry,date";
    cout << "  Input: \"" << csv << "\"" << endl;
    cout << "  Split: ";
    for (const auto& word : split(csv, ',')) {
        cout << "[" << word << "] ";
    }
    cout << endl;
    
    // Example 3: Join strings
    cout << "\nExample 3: Join strings" << endl;
    auto join = [](const vector<string>& vec, const string& delimiter) {
        if (vec.empty()) return string("");
        string result = vec[0];
        for (size_t i = 1; i < vec.size(); i++) {
            result += delimiter + vec[i];
        }
        return result;
    };
    
    vector<string> words = {"Hello", "World", "C++"};
    cout << "  Joined with ' ': \"" << join(words, " ") << "\"" << endl;
    cout << "  Joined with '-': \"" << join(words, "-") << "\"" << endl;
    
    // Example 4: Count words
    cout << "\nExample 4: Count words" << endl;
    auto countWords = [](const string& str) {
        stringstream ss(str);
        string word;
        int count = 0;
        while (ss >> word) count++;
        return count;
    };
    
    string sentence = "The quick brown fox jumps over the lazy dog";
    cout << "  \"" << sentence << "\"" << endl;
    cout << "  Word count: " << countWords(sentence) << endl;
    
    // Example 5: Replace all occurrences
    cout << "\nExample 5: Replace all occurrences" << endl;
    auto replaceAll = [](string str, const string& from, const string& to) {
        size_t pos = 0;
        while ((pos = str.find(from, pos)) != string::npos) {
            str.replace(pos, from.length(), to);
            pos += to.length();
        }
        return str;
    };
    
    string text = "Hello World! Hello C++!";
    cout << "  Original: \"" << text << "\"" << endl;
    cout << "  Replace 'Hello' with 'Hi': \"" << replaceAll(text, "Hello", "Hi") << "\"" << endl;
    
    // Example 6: Title case
    cout << "\nExample 6: Title case" << endl;
    auto toTitleCase = [](string str) {
        bool newWord = true;
        for (char& c : str) {
            if (isspace(c)) {
                newWord = true;
            } else if (newWord) {
                c = toupper(c);
                newWord = false;
            } else {
                c = tolower(c);
            }
        }
        return str;
    };
    
    string title = "the QUICK brown FOX";
    cout << "  Original: \"" << title << "\"" << endl;
    cout << "  Title case: \"" << toTitleCase(title) << "\"" << endl;
    
    // Example 7: Simple regex matching
    cout << "\nExample 7: Regex matching" << endl;
    regex pattern(R"(\d{3}-\d{3}-\d{4})");  // Phone pattern
    
    string phone1 = "123-456-7890";
    string phone2 = "12-34-5678";
    
    cout << "  \"" << phone1 << "\" matches phone pattern: " 
         << boolalpha << regex_match(phone1, pattern) << endl;
    cout << "  \"" << phone2 << "\" matches phone pattern: " 
         << regex_match(phone2, pattern) << endl;
    
    // Example 8: Extract emails
    cout << "\nExample 8: Extract emails using regex" << endl;
    string text2 = "Contact us at info@example.com or support@test.org";
    regex email_pattern(R"(\w+@\w+\.\w+)");
    
    cout << "  From: \"" << text2 << "\"" << endl;
    cout << "  Emails found: ";
    sregex_iterator begin(text2.begin(), text2.end(), email_pattern);
    sregex_iterator end;
    for (auto it = begin; it != end; ++it) {
        cout << it->str() << " ";
    }
    cout << endl;
}

// ============================================================
// Main Function
// ============================================================
int main() {
    cout << "╔═════════════════════════════════════════════════════════════╗" << endl;
    cout << "║          C++ STRINGS - COMPREHENSIVE EXAMPLES              ║" << endl;
    cout << "╚═════════════════════════════════════════════════════════════╝" << endl;
    
    demonstrateCreation();
    demonstrateAccess();
    demonstrateConcatenation();
    demonstrateSearching();
    demonstrateModification();
    demonstrateComparison();
    demonstrateConversion();
    demonstrateAlgorithms();
    demonstrateCStringInterop();
    demonstratePractical();
    
    cout << "\n╔═════════════════════════════════════════════════════════════╗" << endl;
    cout << "║                    END OF EXAMPLES                         ║" << endl;
    cout << "╚═════════════════════════════════════════════════════════════╝" << endl;
    
    return 0;
}
Examples - C++ Tutorial | DeepML