C++ Programming: Objects, RAII and the STL ยท C++ Basics

std::string

C++ strings grow by themselves and know their length. Join, measure, slice, search, change and compare them.

std_string.cpp

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

int main() {
    string first = "Grace";
    string last = "Hopper";
    string full = first + " " + last;
    size_t len = full.length();
    string part = full.substr(0, 5);
    size_t where = full.find("Hop");
    full[0] = 'g';                  // strings in C++ can be changed in place
    bool same = (part == "Grace");
    cout << full << " " << len << " " << where << " " << same << endl;
    return 0;
}

Step by step

  1. C++ enters int main().
  2. A std::string: it manages its own memory and grows as needed.
  3. last is created on the stack with the value "Hopper".
  4. + joins strings into a new one.
  5. len is created on the stack with the value 12.
  6. substr(0, 5): 5 characters starting at 0.
  7. find gives the position where "Hop" starts.
  8. std::string can be changed in place, unlike Java or Python strings.
  9. == compares the text itself, unlike char arrays in C.
  10. It prints grace Hopper 12 6 1.
  11. The method returns 0.
  12. "grace Hopper" 12 6 1.