2. What are classes?
C++
was originally called “C with classes”
A class can be thought of as new type of
variable that you can create.
Just like functions are new operations you
can write, classes are new variables
We’ve
used one kind of class already: the
string class
string and its functions are built into C++.
3. Strings
The
internal construction of a string is
really an array of characters.
To find the length of a string s we can use
the functions .length() or .size
int x = s.length(); gives x the value of the
size of the string s.
To “concatenate” two strings s1 and s2:
string s3 = s1+s2;
4. String examples
string first, last, name;
cout<<"Enter your first name:";
cin>>first;
cout<<"Enter your last name:";
cin>>last;
cout<<"Hi, "+first+" "+last; //concat
5. getline()
cin
reads the typed string only until the first
whitespace.
If you want the whole string including
those whitespaces, you can use:
getline(cin, stringname);
cout<<“Enter
your name:”;
getline(cin, fullname);
Use fullname instead of first and last.
6. “dot” functions
With
strings we start dealing with a new
kind of function call. These functions
operate on a specific “object” (an
instance of a class).
We write the object name (e.g. the
variable name of the string) followed by
period and the function call (no space
before or after the period).
7. More functions
s1.find(string
s2) – returns the index of the
beginning of s2 in s1.
s1 = “hello”;
s1.find(“lo”) – returns 3
s1.insert(int i, string s2) – inserts s2 into s1 at
index I
s1.at(int i) – returns the character at index
i in string s1