๐Ÿง  PART 1: Introduction to C++ std::string

๐Ÿ”น What is std::string?

C++ provides the std::string class (from <string>) for safer and more flexible string handling compared to C-style strings (char[]).

โœ… Basic Syntax:

#include <iostream>
#include <string>
using namespace std;

int main() {
    string s1 = "Hello";
    string s2("World");

    cout << s1 + " " + s2 << endl; // Hello World
    return 0;
}

๐Ÿงช Letโ€™s Learn by Doing

๐Ÿ”น Example 1: Concatenation, Length, and Iteration

#include <iostream>
#include <string>
using namespace std;

int main() {
    string name = "Smarty";
    name += " is learning C++ strings!";

    cout << "Message: " << name << endl;
    cout << "Length: " << name.length() << endl;

    cout << "Characters: ";
    for (char c : name) {
        cout << c << " ";
    }
    cout << endl;

    return 0;
}

๐Ÿ”น Example 2: Substring, Find, and Replace

#include <iostream>
#include <string>
using namespace std;

int main() {
    string text = "I love coding in C++.";

    size_t pos = text.find("coding");
    if (pos != string::npos) {
        text.replace(pos, 6, "building");
    }

    string lang = text.substr(text.find("C++"), 3);  // "C++"
    cout << "Updated: " << text << endl;
    cout << "Language: " << lang << endl;

    return 0;
}

๐Ÿ”น Example 3: Erase, Insert, Compare

#include <iostream>
#include <string>
using namespace std;

int main() {
    string s = "Code at scale";

    s.insert(5, "like a pro ");   // after 'Code '
    s.erase(0, 5);                // remove "Code "

    cout << s << endl;

    string a = "abc", b = "xyz";
    if (a < b) cout << "abc comes before xyz\\n";

    return 0;
}