String class : C++

#include <iostream>
#include <string>
using namespace std;
int main()
{
    //string intialization
    string s0;
    string s1("Mei");
    string s2 = "Meikandanathan";
    string s3(s1);
    string s4 = s2;
    char arr[] = {'a', 'b', 'c', '\0'};
    string s5(arr);
    cout << s0 << endl;
    cout << s1 << endl;
    cout << s2 << endl;
    cout << s3 << endl;
    cout << s4 << endl;
    cout << s5 << endl;
    //Check empty string
    if (s0.empty())
        cout << "s0 is an empty string" << endl;
    //Append
    s0.append("I'm appended to s0 string");
    s0 += " and I'm concatenated to s0";
    cout << s0 << endl;
    //Remove
    cout << s0.length() << endl;
    s0.clear();
    cout << s0.length() << endl;
    //Compare
    s0 = "Flower";
    s1 = "Fruit";
    //0 - equal
    //+number - s0 is lexicographically greater than s1
    //-number - s0 is lexicographically smaller than s1
    cout << s0.compare(s1) << endl;
    //Accessing
    cout << s0[1] << endl;
    //Find substrings
    string s6 = "I'm want to become a master in competitive programming";
    int index = s6.find("master");
    cout << index << endl;
    //Remove a word from the string
    string word = "master";
    s6.erase(index, word.length() + 1);
    cout << s6 << endl;
    //Iterate over all characters in strings
    string s7 = "Happy";
    for (int i = 0; i < s7.length(); i++)
    {
        cout << s7[i] << " " << endl;
    }
    //Iterators
    for (auto itr = s7.begin(); itr != s7.end(); itr++)
    {
        cout << *itr << " ";
    }
    cout << endl;
    //For each
    for (char c : s7)
        cout << c << "-";
    return 0;
}

Leave a Comment

Your email address will not be published. Required fields are marked *