// This example demonstrates some string stuff
#include <string>
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
// The constructor
string x;
string y = "Have a nice day";
string z("There ya go");
// size() & length()
cout << __LINE__ << ": " << x.size() << ' ' << y.size() << endl;
cout << __LINE__ << ": " << x.length() << ' ' << y.length() << endl;
// clear()
cout << __LINE__ << ": " << y << endl;
y.clear();
cout << "y=" << y << endl;
cout << "y.size()=" << y.size() << endl;
// find
size_t pos;
pos = z.find("ya");
cout << __LINE__ << ": " << pos << endl;
cout << __LINE__ << ": " << z.find('g') << endl;
cout << __LINE__ << ": " << z.find("ZZZ") << endl;
// npos is a constant member of the string class
x = "ZZZ";
if (z.find(x) == string::npos)
cout << "Can't find " << x << endl;
// substr()
x = z.substr(0,7);
cout << __LINE__ << ": " << x << endl;
y = z.substr(8);
cout << __LINE__ << ": " << y << endl;
z = z.substr(1);
cout << __LINE__ << ": " << z << endl;
// index operator
cout << z[0] << z[1] << z[5] << endl;
x = "Hey";
// Plus-equal operator
x += " y'all";
cout << x << endl;
// Plus operator (not a member of string class)
cout << __LINE__ << ": " << x + '!' << endl;
cout << __LINE__ << ": " << x << endl;
y = "Wow! " + x;
cout << __LINE__ << ": " << y << endl;
cout << __LINE__ << ": " << x + y << endl;
// getline (not a member function)
ifstream fin("string_class_demo.cpp");
if (fin)
{
getline(fin,x);
cout << x << endl;
getline(fin,x,'>');
cout << x << endl;
}
}